【问题标题】:Check Existance of a file located in some http link in node.js检查位于 node.js 中某个 http 链接中的文件是否存在
【发布时间】:2013-08-28 18:13:09
【问题描述】:
【问题讨论】:
标签:
node.js
http
file-exists
【解决方案1】:
这有点晚了,但为什么不直接使用http?此方法应该只下载标题而不是整个文件。
// Import HTTP module
var http = require ("http");
// Set request options
var options = { method: "HEAD", host: "example.com", port: 80, path: "test.csv" };
// Initialize HTTP request
var request = http.request ( options, function ( response ) {
console.log ( "Status Code: " + response.statusCode );
});
// End request
request.end ();
【解决方案2】:
最简单的方法是对该 URI 执行 HTTP GET 请求,响应为 200 OK,文件存在,否则不存在。
request.js 在这种情况下可能会很方便,代码:
var request = require('request'); // include request module
request('http://xxxxxx.com/test.csv', function (err, resp) {
if (resp.statusCode === 200) {
return // file exist
}
// file does not exist
});