如何在nodejs中使用url获取文件大小

时间:2018-04-03 14:15:01

标签: javascript node.js keystonejs

我在网址中有一些图片。我可以获取文件属性和属性包括图像的宽度和高度。我希望以字节获得大小。

我正在尝试使用fs模块获取大小,如下所示,但它不能与url一起使用,尽管它适用于本地文件夹中的文件路径。

var stats = fs.statSync(url);
var fileSizeInBytes = stats["size"]

2 个答案:

答案 0 :(得分:3)

您必须使用requesthttp。您可以通过发送HEAD请求并检查content-length字段来获取文件大小(它不适用于每台服务器):

使用curl

curl -I "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/core.js"

你收到回复:

HTTP/1.1 200 OK
Date: Tue, 03 Apr 2018 14:30:16 GMT
Content-Type: application/javascript; charset=utf-8
Content-Length: 9068
Connection: keep-alive
Last-Modified: Wed, 28 Feb 2018 04:16:30 GMT
ETag: "5a962d1e-236c"
Expires: Sun, 24 Mar 2019 14:30:16 GMT
Cache-Control: public, max-age=30672000
Access-Control-Allow-Origin: *
CF-Cache-Status: HIT
Accept-Ranges: bytes
Strict-Transport-Security: max-age=15780000; includeSubDomains
Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
Server: cloudflare
CF-RAY: 405c3b6e1911a8db-CDG

使用request模块:

var request = require("request");

request({
    url: "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/core.js",
    method: "HEAD"
}, function(err, response, body) {
    console.log(response.headers);
    process.exit(0);
});

你收到回复:

{
  date: 'Tue, 03 Apr 2018 14:29:32 GMT',
  'content-type': 'application/javascript; charset=utf-8',
  'content-length': '9068',
  connection: 'close',
  'last-modified': 'Wed, 28 Feb 2018 04:16:30 GMT',
  etag: '"5a962d1e-236c"',
  expires: 'Sun, 24 Mar 2019 14:29:32 GMT',
  'cache-control': 'public, max-age=30672000',
  'access-control-allow-origin': '*',
  'cf-cache-status': 'HIT',
  'accept-ranges': 'bytes',
  'strict-transport-security': 'max-age=15780000; includeSubDomains',
  'expect-ct': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"',
  server: 'cloudflare',
  'cf-ray': '405c3a5cba7a68ba-CDG'
}

答案 1 :(得分:0)

将图像下载到临时/tmp/目录,然后将其视为常规文件。

const request    = require("request"),
      fs         = require("fs"),
      remote_url = "https://example.com/image.jpg",
      path       = '/tmp/media.jpg',
      media      = request(remote_url).pipe(fs.createWriteStream(path));

media.on("finish", () => {
  return fs.statSync(path).size;
});