如何检查文件是否存在?
当前回答
关于fs.existsSync()被弃用有很多不准确的评论;事实并非如此。
https://nodejs.org/api/fs.html#fs_fs_existssync_path
注意fs.exists()已弃用,但fs.existsSync()未弃用。
其他回答
fs。Exists自1.0.0以来已弃用。你可以用fs。用统计代替。
var fs = require('fs');
fs.stat(path, (err, stats) => {
if ( !stats.isFile(filename) ) { // do this
}
else { // do this
}});
这里是文档的链接 fs.stats
考虑直接打开或读取文件,以避免竞争条件:
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')) {
// ...
}
@狐狸:回答得好! 这里有一个扩展,有更多的选项。这是我最近一直在使用的解决方案:
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)
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)其他库都依赖于它。
一种更简单的同步方法。
if (fs.existsSync('/etc/file')) {
console.log('Found file');
}
API文档说明了existsSync是如何工作的: 通过检查文件系统来测试给定路径是否存在。
推荐文章
- 有没有办法修复包锁。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