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
Add a comment  | 

2 Answers 2

Reset to default 14

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

本文标签: javascriptNode Js How to catch a quotNo such file or directoryquot error in readline moduleStack Overflow