如何检查文件是否存在?
当前回答
考虑直接打开或读取文件,以避免竞争条件:
const fs = require('fs');
fs.open('foo.txt', 'r', (err, fd) => {
// ...
});
fs.readFile('foo.txt', (err, data) => {
if (!err && data) {
// ...
}
})
使用fs.existsSync:
if (fs.existsSync('foo.txt')) {
// ...
}
使用fs.stat:
fs.stat('foo.txt', function(err, stat) {
if (err == null) {
console.log('File exists');
} else if (err.code === 'ENOENT') {
// file does not exist
fs.writeFile('log.txt', 'Some log\n');
} else {
console.log('Some other error: ', err.code);
}
});
弃用:
fs。Exists已弃用。
使用path.exists:
const path = require('path');
path.exists('foo.txt', function(exists) {
if (exists) {
// ...
}
});
使用path.existsSync:
if (path.existsSync('foo.txt')) {
// ...
}
其他回答
现代异步/等待方式(Node 12.8. net)。x)
const fileExists = async path => !!(await fs.promises.stat(path).catch(e => false));
const main = async () => {
console.log(await fileExists('/path/myfile.txt'));
}
main();
我们需要使用fs.stat()或fs.access(),因为fs。Exists (path, callback)现在已弃用
另一个好方法是fs-extra
2021年8月
读完所有帖子后:
let filePath = "./directory1/file1.txt";
if (fs.existsSync(filePath)) {
console.log("The file exists");
} else {
console.log("The file does not exist");
}
考虑直接打开或读取文件,以避免竞争条件:
const fs = require('fs');
fs.open('foo.txt', 'r', (err, fd) => {
// ...
});
fs.readFile('foo.txt', (err, data) => {
if (!err && data) {
// ...
}
})
使用fs.existsSync:
if (fs.existsSync('foo.txt')) {
// ...
}
使用fs.stat:
fs.stat('foo.txt', function(err, stat) {
if (err == null) {
console.log('File exists');
} else if (err.code === 'ENOENT') {
// file does not exist
fs.writeFile('log.txt', 'Some log\n');
} else {
console.log('Some other error: ', err.code);
}
});
弃用:
fs。Exists已弃用。
使用path.exists:
const path = require('path');
path.exists('foo.txt', function(exists) {
if (exists) {
// ...
}
});
使用path.existsSync:
if (path.existsSync('foo.txt')) {
// ...
}
你可以用fs。Stat检查目标是否为文件或目录,您可以使用fs。访问,检查是否可以写入/读取/执行文件。(记得使用path。决心获得目标的完整路径)
文档:
path.resolve fs.stat fs.access
完整示例(TypeScript)
import * as fs from 'fs';
import * as path from 'path';
const targetPath = path.resolve(process.argv[2]);
function statExists(checkPath): Promise<fs.Stats> {
return new Promise((resolve) => {
fs.stat(checkPath, (err, result) => {
if (err) {
return resolve(undefined);
}
return resolve(result);
});
});
}
function checkAccess(checkPath: string, mode: number = fs.constants.F_OK): Promise<boolean> {
return new Promise((resolve) => {
fs.access(checkPath, mode, (err) => {
resolve(!err);
});
});
}
(async function () {
const result = await statExists(targetPath);
const accessResult = await checkAccess(targetPath, fs.constants.F_OK);
const readResult = await checkAccess(targetPath, fs.constants.R_OK);
const writeResult = await checkAccess(targetPath, fs.constants.W_OK);
const executeResult = await checkAccess(targetPath, fs.constants.X_OK);
const allAccessResult = await checkAccess(targetPath, fs.constants.F_OK | fs.constants.R_OK | fs.constants.W_OK | fs.constants.X_OK);
if (result) {
console.group('stat');
console.log('isFile: ', result.isFile());
console.log('isDir: ', result.isDirectory());
console.groupEnd();
}
else {
console.log('file/dir does not exist');
}
console.group('access');
console.log('access:', accessResult);
console.log('read access:', readResult);
console.log('write access:', writeResult);
console.log('execute access:', executeResult);
console.log('all (combined) access:', allAccessResult);
console.groupEnd();
process.exit(0);
}());
在node14中使用typescript和fs/promises
import * as fsp from 'fs/promises';
try{
const = await fsp.readFile(fullFileName)
...
} catch(e) { ...}
最好使用fsp。readFile than fsp。定子fsp。访问有两个原因:
最不重要的原因是少了一个机会。 有可能fsp。statand fsp。readFile会给出不同的答案。要么是因为他们所问问题的细微差异,要么是因为文件状态在两次调用之间发生了变化。因此编码器必须为两个而不是一个条件分支编码,用户可能会看到更多的行为。
推荐文章
- 有没有办法修复包锁。json lockfileVersion所以npm使用特定的格式?
- 如何使用npm全局安装一个模块?
- 实时http流到HTML5视频客户端的最佳方法
- 使用node.js下载图像
- Node.js Express中的HTTP GET请求
- Node.js:将文本文件读入数组。(每一行都是数组中的一项。)
- npm犯错!错误:EPERM:操作不允许,重命名
- Node Sass还不支持当前环境:Linux 64位,带false
- 我如何添加环境变量启动。VSCode中的json
- 解析错误:无法读取文件“…/tsconfig.json”.eslint
- 在Node.js中'use strict'语句是如何解释的?
- 当WebSockets可用时,为什么要使用AJAX ?
- 使用过程。TypeScript中的env
- 如何找到哪些承诺未处理在Node.js UnhandledPromiseRejectionWarning?
- 如何卸载Yarn