Javascript 如何在 Node.js 中找到文件的大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42363140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:05:46  来源:igfitidea点击:

How to find the size of the file in Node.js?

javascriptnode.jsexpressmulter

提问by Daniel

I am using multer for uploading my images and documents but this time I want to restrict uploading if the size of the image is >2mb. How can I find the size of the file of the document? So far I tried as below but not working.

我正在使用 multer 上传我的图像和文档,但这次我想限制上传,如果图像的大小大于 2mb。如何找到文档文件的大小?到目前为止,我尝试如下但没有工作。

var storage = multer.diskStorage({
      destination: function (req, file, callback) {
        callback(null, common.upload.student);
      },
      filename: function (req, file, callback) {  
        console.log(file.size+'!!!!!!!!!!!!!!')======>'Undefined'
        var ext = '';
        var name = '';
        if (file.originalname) {
          var p = file.originalname.lastIndexOf('.');
          ext = file.originalname.substring(p + 1);
          var firstName = file.originalname.substring(0, p + 1);
          name = Date.now() + '_' + firstName;
          name += ext;
        }
        var filename = file.originalname;
        uploadImage.push({ 'name': name });
        callback(null, name);
  }
});

Can anyone please help me?

谁能帮帮我吗?

回答by Jameel

var fs = require("fs"); //Load the filesystem module
var stats = fs.statSync("myfile.txt")
var fileSizeInBytes = stats["size"]
//Convert the file size to megabytes (optional)
var fileSizeInMegabytes = fileSizeInBytes / 1000000.0

or:

或者:

function getFilesizeInBytes(filename) {
    var stats = fs.statSync(filename)
    var fileSizeInBytes = stats["size"]
    return fileSizeInBytes
}

回答by gerryamurphy

In addition, you can use the NPM filesize package: https://www.npmjs.com/package/filesize

另外,你可以使用 NPM filesize 包:https: //www.npmjs.com/package/filesize

This package makes things a little more configurable.

这个包使事情变得更加可配置。

var fs = require("fs"); //Load the filesystem module

var filesize = require("filesize"); 

var stats = fs.statSync("myfile.txt")

var fileSizeInMb = filesize(stats.size, {round: 0});

For more examples:
https://www.npmjs.com/package/filesize#examples

更多示例:https:
//www.npmjs.com/package/filesize#examples

回答by Dawson B

The link above by @gerryamurphy is broken for me, so I will link to a package I made for this.

@gerryamurphy 上面的链接对我来说已损坏,因此我将链接到我为此制作的包。

https://github.com/dawsbot/file-bytes

https://github.com/dawsbot/file-bytes

The API is simple and should be easily usable:

API 很简单,应该很容易使用:

fileBytes('README.md').then(size => { console.log(`README.md is ${size} bytes`); });

fileBytes('README.md').then(size => { console.log(`README.md is ${size} bytes`); });

Let me know if you need any help!

如果您需要任何帮助,请告诉我!

回答by Nadav

If you only need to find the size of one file in bytes it only takes 2 lines (one if the fs module is already declared):

如果您只需要以字节为单位查找一个文件的大小,则只需 2 行(如果 fs 模块已经声明,则为 1 行):

const fs = require('fs');
const {size} = fs.statSync('path/to/file');

回答by Lucaci Andrei

You can also check this package from npm: https://www.npmjs.com/package/file-sizeof

你也可以从 npm 中查看这个包:https://www.npmjs.com/package/file-sizeof

The API is quite simple, and it gives you the file size in SIand IECnotation.

API 非常简单,它为您提供文件大小SIIEC符号。

const { sizeof } = require("file-sizeof");

const si = sizeof.SI("./testfile_large.mp4");
const iec = sizeof.IEC("./testfile_large.mp4");

And the resulting object represents the size from B(byte) up to PB(petabyte).

结果对象表示从B(byte) 到PB(petabyte) 的大小。

interface ISizeOf {
  B: number;
  KB: number;
  MB: number;
  GB: number;
  TB: number;
  PB: number;
}

回答by Fall Bay

Using the following:

使用以下内容:

window.require("fs")

window.require("fs")

Instead of just:

而不仅仅是:

require("fs")

require("fs")

Resolved this issue for me.

为我解决了这个问题。