How to find file size in Node.js?

I use multer to upload my images and documents, but this time I want to limit the download if the image size is> 2mb. How to find document file size? So far I have tried, as shown below, but have not worked.

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 anybody help me?

+11
source share
3 answers
 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 } 
+17
source

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

This package makes things a little more customizable.

 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}); 

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

0
source

The link above @gerryamurphy does not work for me, so I will make a link to the package I made for this.

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

The API is simple and should be easy to use:

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

Let me know if you need any help!

0
source

Source: https://habr.com/ru/post/1264501/


All Articles