ubi*_*biQ 18 javascript node.js
我正在尝试调用fs.exists节点脚本,但我得到错误:
TypeError:对象#没有方法'存在'
我试着更换fs.exists()用require('fs').exists,甚至require('path').exists(以防万一),但这些都不甚至列表的方法exists()与我的IDE.fs在我的脚本的顶部声明,fs = require('fs');我以前用它来读取文件.
我该怎么打电话exists()?
los*_*rce 21
您的require语句可能不正确,请确保您拥有以下内容
var fs = require("fs");
fs.exists("/path/to/file",function(exists){
// handle result
});
Run Code Online (Sandbox Code Playgroud)
阅读此处的文档
http://nodejs.org/api/fs.html#fs_fs_exists_path_callback
War*_*rad 16
你应该使用fs.stats或fs.access代替.从节点文档中,不推荐使用exists(可能已删除.)
如果您尝试做的不仅仅是检查存在,那么文档说要使用fs.open.举个例子
fs.access('myfile', (err) => {
if (!err) {
console.log('myfile exists');
return;
}
console.log('myfile does not exist');
});
Run Code Online (Sandbox Code Playgroud)
不要使用fs.exists 请阅读其API文档以供替代
这是建议的替代方案:继续并打开文件,然后处理错误,如果有的话:
var fs = require('fs');
var cb_done_open_file = function(interesting_file, fd) {
console.log("Done opening file : " + interesting_file);
// we know the file exists and is readable
// now do something interesting with given file handle
};
// ------------ open file -------------------- //
// var interesting_file = "/tmp/aaa"; // does not exist
var interesting_file = "/some/cool_file";
var open_flags = "r";
fs.open(interesting_file, open_flags, function(error, fd) {
if (error) {
// either file does not exist or simply is not readable
throw new Error("ERROR - failed to open file : " + interesting_file);
}
cb_done_open_file(interesting_file, fd);
});
Run Code Online (Sandbox Code Playgroud)
正如其他人指出的那样,fs.exists已被弃用,部分原因是它使用单个(success: boolean)参数,而不是几乎(error, result)其他地方都存在的更常见的参数。
但是,fs.existsSync它并没有被弃用(因为它不使用回调,它只是返回一个值),并且如果脚本的整个其余部分依赖于检查单个文件的存在,那么它可以使事情变得比必须处理更容易回调或用try/包围调用catch(在 的情况下accessSync):
const fs = require('fs');
if (fs.existsSync(path)) {
// It exists
} else {
// It doesn't exist
}
Run Code Online (Sandbox Code Playgroud)
当然existsSync是同步和阻塞。虽然这有时很方便,但如果您需要并行执行其他操作(例如一次检查多个文件是否存在),则应该使用其他基于回调的方法之一。
现代版本的 Node 还支持基于 Promise 的fs方法版本,人们可能更喜欢这种版本而不是回调:
fs.promises.access(path)
.then(() => {
// It exists
})
.catch(() => {
// It doesn't exist
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46299 次 |
| 最近记录: |