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

Dan*_*iel 22 javascript node.js express multer

我正在使用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);
  }
});
Run Code Online (Sandbox Code Playgroud)

谁能帮帮我吗?

小智 43

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
Run Code Online (Sandbox Code Playgroud)

要么:

function getFilesizeInBytes(filename) {
    var stats = fs.statSync(filename)
    var fileSizeInBytes = stats["size"]
    return fileSizeInBytes
}
Run Code Online (Sandbox Code Playgroud)

  • 对于 2020 年以后搜索的人,我们现在有“(await fs.promises.stat(file)).size”。 (15认同)
  • 您的转换为mb除以1024 ^ 2吗? - 请参阅[此答案](/sf/ask/1113033981/)进行深入分析转换 (5认同)
  • 为了方便起见,链接到官方文档:[fs.stat](https://nodejs.org/api/fs.html#fs_fs_stat_path_options_callback) 和 [fs.promises.stat](https://nodejs.org/api/fs. html#fs_fspromises_stat_path_options) (2认同)

Nad*_*dav 9

If you use ES6 and deconstructing, finding the size of a file in bytes only takes 2 lines (one if the fs module is already declared!):

const fs = require('fs');
const {size} = fs.statSync('path/to/file');
Run Code Online (Sandbox Code Playgroud)

Note that this will fail if the size variable was already declared. This can be avoided by renaming the variable while deconstructing using a colon:

const fs = require('fs');
const {size: file1Size} = fs.statSync('path/to/file1');
const {size: file2Size} = fs.statSync('path/to/file2');
Run Code Online (Sandbox Code Playgroud)


小智 6

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

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

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});
Run Code Online (Sandbox Code Playgroud)

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