node.js - 从 accessSync 返回 ENOENT 以外的值
问题描述
当它找不到文件/目录而不是时,false
我将如何返回?accessSync
ENOENT
单元测试
it.only('should be able to read a file stream only if a file exist', function() {
let testfile = testpath+'/imageeee.png';
let ok = FileService.existsAsync(testfile);
ok = ok.then((result) => {
console.log('exists: ', result);
return FileService.createReadStream(testfile);
});
ok = ok.then((result) => {
assert.isNotNull(result.path);
assert.equal(result.path, testfile);
assert.isTrue(result.readable, true);
});
return ok;
});
功能
existsAsync(path) {
let ok = fs.accessAsync(path, fs.F_OK);
ok = ok.then(function(error) {
if (error) {
return false;
} else {
return true;
}
});
return ok;
},
错误
Error: ENOENT: no such file or directory, access '/home/j/Work/imageeee.png'
解决方案
将此视为替代解决方案,通过使用带有 cat 的 'child_process' 而不是 'fs' 功能来了解文件是否存在(实际捕获错误异常不会干扰您的主要当前进程),从而避免 ENOENT 错误。
const { exec } = require('child_process');
function is_file(path){
return new Promise(resolve => {
try {
exec(`cat ${path}`, (err, stdout, stderr) => { // cat required
if (err) {
resolve(false);
} else {
resolve(true);
}
});
} catch ( e ) { resolve(false); }
});
}
async function main(){
let file = `foo.txt`;
if ( (await is_file(file)) ) {
console.log(`file exists: ${file}`);
} else {
console.log(`no such file: ${file}`);
}
}
main();
推荐阅读
- rest - 如何通过rest api从yammer中提取基于人口统计的活动?
- c# - DataTable.AsEnumerable() 中的 C# Nullreferenceexception 在哪里
- cucumber - 如何为所有 Cucumber 步骤添加默认超时?
- reactjs - 优化组件树
- react-native - Native Base - 放置在 Header 中的组件不是垂直居中的 react-native
- java - 调用对象时,这些括号是什么意思?
- javascript - Google Analytics Reporting API:Javascript 中的活跃用户数
- c# - .NET Core 2 项目的 StackExchange.Exceptional 错误的 URL 是什么?
- html - 如何处理多选项卡式 html 表单上的验证,我如何知道存在验证错误
- javascript - 通过 jquery 选择单选按钮(按值或按 id)