admin管理员组文章数量:1220497
I'm working on a program that reads a file line by line with the readline module. First I get the file name by command line, but I want to check if the file actually exists. I have read about fs.stat() but I want to know if there is a way to catch the error directly with readline. So far I've tried this
try{
var line_reader = read_line.createInterface({
input: file_stream.createReadStream(file_name)
});
}catch(err){
console.log('Please insert a valid file name');
}
But I still get the message
Error: ENOENT: no such file or directory
I'm working on a program that reads a file line by line with the readline module. First I get the file name by command line, but I want to check if the file actually exists. I have read about fs.stat() but I want to know if there is a way to catch the error directly with readline. So far I've tried this
try{
var line_reader = read_line.createInterface({
input: file_stream.createReadStream(file_name)
});
}catch(err){
console.log('Please insert a valid file name');
}
But I still get the message
Error: ENOENT: no such file or directory
Share
Improve this question
asked May 18, 2016 at 21:47
Julio BastidaJulio Bastida
1,2191 gold badge15 silver badges30 bronze badges
2 Answers
Reset to default 14The exception is thrown by createReadStream. You need to add 'on error' case to createReadStream:
var fs = file_stream.createReadStream(file_name)
fs.on('error', function (err) {
// handle error here
});
var line_reader = read_line.createInterface({
input: fs
});
Miss read your question at the beginning and updated my answer.
A solution you could use fs.stat
Edit
// fs.stat is async
fs.stat(file_name, function(err,stat){
if (stat && stat.isFile() ) {
var line_reader = read_line.createInterface({
input: file_stream.createReadStream(file_name)
});
}
});
版权声明:本文标题:javascript - Node Js: How to catch a "No such file or directory" error in readline module - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739272087a2155858.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论