节点Js:How to catch a“;没有这样的文件或目录“;读取线模块出错

Node Js: How to catch a "No such file or directory" error in readline module

本文关键字:文件 出错 模块 读取 How Js to catch 节点      更新时间:2023-09-26

我正在开发一个程序,该程序使用readline模块逐行读取文件。首先,我通过命令行获取文件名,但我想检查该文件是否真的存在。我读过fs.stat(),但我想知道是否有一种方法可以直接用readline捕获错误。到目前为止,我已经尝试过这个

try{
 var line_reader = read_line.createInterface({
  input: file_stream.createReadStream(file_name)
 });
}catch(err){
 console.log('Please insert a valid file name');
}

但我仍然收到的消息

Error: ENOENT: no such file or directory

异常由createReadStream引发。您需要添加"出现错误"的情况来创建ReadStream:

var fs = file_stream.createReadStream(file_name)
fs.on('error', function (err) {
                // handle error here
            });
 var line_reader = read_line.createInterface({
  input: fs
 });

小姐从一开始就阅读了你的问题,并更新了我的答案。

可以使用fs.stat 的解决方案

编辑

// 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)
      });
   }
});