[英]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.我正在使用 multer 上传我的图片和文档,但这次我想限制上传图片的大小是否大于 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?谁能帮帮我吗?
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;
}
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:):如果你使用 ES6 和解构,找到一个文件的字节大小只需要 2 行(如果已经声明了 fs 模块:):
const fs = require('fs');
const {size} = fs.statSync('path/to/file');
Note that this will fail if the size variable was already declared.请注意,如果已声明 size 变量,这将失败。 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');
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
For anyone looking for a current answer with native packages, here's how to get mb size of a file without blocking the event loop using fs
(specifically, fsPromises ) and async
/ await
:对于任何使用本机包寻找当前答案的人,这里是如何使用
fs
(特别是fsPromises )和async
/ await
获取文件的 mb 大小而不阻塞事件循环:
const fs = require('fs').promises;
const BYTES_PER_MB = 1024 ** 2;
// paste following snippet inside of respective `async` function
const fileStats = await fs.stat('/path/to/file');
const fileSizeInMb = fileStats.size / BYTES_PER_MB;
The link 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`);
});
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 SI
and IEC
notation. API 非常简单,它以
SI
和IEC
符号为您提供文件大小。
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
(字节)到PB
(拍字节)的大小。
interface ISizeOf {
B: number;
KB: number;
MB: number;
GB: number;
TB: number;
PB: number;
}
You can find the size in bytes.您可以找到以字节为单位的大小。
const libFS = require('fs');
let yourFilesize = fs.statSync("File path").size
console.log(yourFilesize)
NOTE: The following is within the context of an Electron application.注意:以下是在 Electron 应用程序的上下文中。
Using the following:使用以下内容:
window.require("fs")
Instead of just:而不仅仅是:
require("fs")
Resolved this issue for me.为我解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.