You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
964 B
JavaScript

"use strict";
const Promise = require("bluebird");
const fs = require("fs");
function analyzeBuffer(buffer) {
return buffer.length;
}
function analyzeBlob(blob) {
return blob.size;
}
function analyzeStream(stream) {
return Promise.try(() => {
return fs.promises.stat(stream.path);
}).then((stat) => {
return stat.size;
});
}
function analyzeString(string) {
// NOTE: string.length would produce the size in *code units*, but we want the size in *bytes*
return (new TextEncoder().encode(string)).length;
}
module.exports = function getFilesize(file) {
if (typeof file === "string") {
return analyzeString(file);
} else if (typeof Blob !== "undefined" && file instanceof Blob) {
return analyzeBlob(file);
} else if (Buffer.isBuffer(file)) {
return analyzeBuffer(file);
} else if (file._readableState != null && file.path != null) {
return analyzeStream(file);
} else {
throw new Error(`Invalid file passed`); // FIXME: Validate
}
};