我在节点中使用此代码来检查文件是否不是以点开头
if( !file.startsWith('.') ){...}
无论如何,它似乎工作正常,我还需要检查文件的大小是否不大于 2GB。我怎么能做到这一点?像这样的东西会起作用吗?
if( !file.startsWith('.') || fs.statSync(`${filesPath}${file}`).size < 2048 ){...}
答案 0 :(得分:3)
如果您想确保文件不以点开头并且小于 2GB,则此代码应该可以满足您的需求:
const GIGABYTE = Math.pow(1024, 3);
const MAX_SIZE = 2 * GIGABYTE;
const filePath = path.join(filesPath, file);
console.log( { filePath });
if (!file.startsWith('.') && fs.statSync(filePath).size <= MAX_SIZE ) {
console.log("File is below max size and does not start with a dot.")
} else {
console.log("File is above max size or starts with a dot.")
}
你也可以像这样拆分逻辑:
const filePath = path.join(filesPath, file);
if (file.startsWith(".")) {
console.log("File starts with a dot.")
} else if (fs.statSync(filePath).size > MAX_SIZE) {
console.log("File is above max size.")
} else {
// File is good
console.log("File is below max size and does not start with a dot.")
}