Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

node读取文件失败怎么处理?

用fs.createReadStream和fs.readFileSync读取文件

但是一旦文件没有找到
就会报错

2020-12-23 16:42:44,082 ERROR 25598 nodejs.ENOENTError: ENOENT: no such file or directory, open '/Users/laiyinan/Desktop/2020114/jpg/UG1NBQF1_1604470696777.jpg' (uncaughtException throw 1 times on pid:25598)
ENOENTError: ENOENT: no such file or directory, open '/Users/laiyinan/Desktop/2020114/jpg/UG1NBQF1_1604470696777.jpg' (uncaughtException throw 1 times on pid:25598)
errno: -2
code: "ENOENT"
syscall: "open"
path: "/Users/laiyinan/Desktop/2020114/jpg/UG1NBQF1_1604470696777.jpg"
name: "ENOENTError"
pid: 25598
hostname: laiyinandeMacBook-Pro.local

报错以后node就会退出 也就是整个后台都崩了

尝试用try catch包住 还是一样

如何处理?

报错的截图:
image


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

我没复现你的问题,我这是可以 try-catch 住的,try-catch 之后的代码也可以正常执行,node 进程也不会崩掉:

var fs = require('fs');

console.log('准备执行 ...');

var fileContents;
try {
    fileContents = fs.readFileSync('test.txt');
} catch (err) {
    if (err && err.code === 'ENOENT') {
        console.log('错误:文件未找到');
    } else {
        console.log('错误:其他原因');
    }
}


console.log('继续执行 ...');
while (true) {
   // 死循环阻止进程结束,比如 WebServer 本质上就是一个死循环不断监听请求
}

image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...