Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

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?

like image 206
Daniel Avatar asked Feb 21 '17 09:02

Daniel


People also ask

What is FS statSync?

The fs. statSync() method is used to synchronously return information about the given file path.

How do I get the size of a file in react native?

let fileInfo = getFileInfo('path/to/my/file. txt'); console. log('file size: ' + fileInfo. size); console.


1 Answers

To get a file's size in megabytes:

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 / (1024*1024); 

or in bytes:

function getFilesizeInBytes(filename) {     var stats = fs.statSync(filename);     var fileSizeInBytes = stats.size;     return fileSizeInBytes; } 
like image 117
Jameel Avatar answered Sep 27 '22 23:09

Jameel