2015-10-20 121 views
1

我是NodeJS的新手,我正在使用“Sequest”包来读取SFTP远程文件的内容。它效果很好。但是,如果我试图读取的文件不存在,那么它会抛出异常,并且应用程序不会进一步响应。NodeJS - 使用“Sequest”检查是否存在SFTP远程文件

所以我想在尝试读取文件之前检查文件是否存在。由于我正在使用库函数(sequest.get),因为缺少指定的文件,所以无法处理库方法中发生的异常。

下面是我的代码:

var reader = sequest.get('[email protected]', fileName, opts); 
    reader.setEncoding('utf8'); 
    reader.on('data', function(chunk) { 
         return res.send(chunk); 
    }); 

reader.on('end', function() { 
    console.log('there will be no more data.'); 
}); 

编号:https://github.com/mikeal/sequest#gethost-path-opts

SEQUEST(https://github.com/mikeal/sequest)是一个包装到SSH2 - (https://github.com/mscdex/ssh2)。

任何帮助,非常感谢。谢谢。

回答

1

您可以收听error事件来处理此类情况。

var reader = sequest.get('[email protected]', fileName, opts); 

reader.setEncoding('utf8'); 

reader.on('data', function(chunk) { 
    return res.send(chunk); 
}); 

reader.on('end', function() { 
    console.log('there will be no more data.'); 
}); 

reader.on('error', function() { 
    console.log('file not found or some other error'); 
}); 
+0

非常感谢。这解决了这个问题。我想我需要详细了解I/O流及其事件。 –

相关问题