如何检查文件是否存在?
当前回答
fs.statSync(path, function(err, stat){
if(err == null) {
console.log('File exists');
//code when all ok
}else if (err.code == "ENOENT") {
//file doesn't exist
console.log('not file');
}
else {
console.log('Some other error: ', err.code);
}
});
其他回答
V6之前的旧版本: 下面是文档
const fs = require('fs');
fs.exists('/etc/passwd', (exists) => {
console.log(exists ? 'it\'s there' : 'no passwd!');
});
// or Sync
if (fs.existsSync('/etc/passwd')) {
console.log('it\'s there');
}
更新
V6的新版本:fs.stat的文档
fs.stat('/etc/passwd', function(err, stat) {
if(err == null) {
//Exist
} else if(err.code == 'ENOENT') {
// NO 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')) {
// ...
}
vannilla Nodejs 回调
function fileExists(path, cb){
return fs.access(path, fs.constants.F_OK,(er, result)=> cb(!err && result)) //F_OK checks if file is visible, is default does no need to be specified.
}
文档说你应该使用access()来代替已弃用的exists()
带有内置承诺的Nodejs (node 7+)
function fileExists(path, cb){
return new Promise((accept,deny) =>
fs.access(path, fs.constants.F_OK,(er, result)=> cb(!err && result))
);
}
流行的javascript框架
fs-extra
var fs = require('fs-extra')
await fs.pathExists(filepath)
如你所见,简单多了。与promisify相比,它的优势在于你可以使用这个包实现完整的类型(完整的智能感知/typescript)!大多数情况下,您已经包含了这个库,因为(+-10.000)其他库都依赖于它。
@狐狸:回答得好! 这里有一个扩展,有更多的选项。这是我最近一直在使用的解决方案:
var fs = require('fs');
fs.lstat( targetPath, function (err, inodeStatus) {
if (err) {
// file does not exist-
if (err.code === 'ENOENT' ) {
console.log('No file or directory at',targetPath);
return;
}
// miscellaneous error (e.g. permissions)
console.error(err);
return;
}
// Check if this is a file or directory
var isDirectory = inodeStatus.isDirectory();
// Get file size
//
// NOTE: this won't work recursively for directories-- see:
// http://stackoverflow.com/a/7550430/486547
//
var sizeInBytes = inodeStatus.size;
console.log(
(isDirectory ? 'Folder' : 'File'),
'at',targetPath,
'is',sizeInBytes,'bytes.'
);
}
另外,如果你还没有用过fs-extra,那就试试吧——它真的很贴心。 https://github.com/jprichardson/node-fs-extra)
异步等待风格的简洁解决方案:
import { stat } from 'fs/promises';
const exists = await stat('foo.txt')
.then(() => true)
.catch(() => false);
推荐文章
- 有没有办法修复包锁。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