【问题标题】:Check Existance of a file located in some http link in node.js检查位于 node.js 中某个 http 链接中的文件是否存在
【发布时间】:2013-08-28 18:13:09
【问题描述】:

我在http://example.com/test.csv 中有一个文件。现在我将如何在 Node.js 中检查文件是否存在。请帮助。

【问题讨论】:

  • 你试过什么?你读过the docs吗? (提示:fs.exists 可能会有所帮助)
  • fs.exits 如果文件路径在本地服务器中有效。但在我的情况下,文件在远程服务器中,即xxxxxx.com/test.csv
  • 您需要下载它来检查或使用HEAD 检查。 stackoverflow.com/a/14552721/95190

标签: 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
    });
    

    【讨论】:

    • 另外,无需下载即可检查是否存在网页内容。
    猜你喜欢
    • 2014-06-08
    • 2013-11-09
    • 2012-02-23
    • 2012-12-19
    • 2013-07-15
    • 1970-01-01
    • 2014-01-20
    • 2014-04-16
    • 1970-01-01
    相关资源
    最近更新 更多