node.js - fs.readFileSync doesn't do anything in case the file doesn't exist -


i trying read content of file code:

 var content = fs.readfilesync(filename); 

it works fine when file such filename exists. however, doesn't if file doesn't exist. hangs there forever.

one solution check if file exists before try read it, hoping part of fs module return undefined or error conveniently handle.

this entire code, can see issues? can't.

for (var i=0; i<configfiles.length;i++){     waterfallmain(configfiles[i]);    }  //var importdefinition = config.importdefinition; function waterfallmain(configfile){     async.waterfall([             function(callback){                 sftphandler.downloadfile(credentials.host, credentials.username, credentials.password, credentials.path+configfile.importfilename, callback);                 console.log("downloading done. changing file encoding , reading data.");                 readfilesync_encoding(configfile.importfilename, "iso-8859-1", callback);             },             function(filedata, callback) {                 mainprocess(filedata, callback);             },             function(data, callback) {                 postimportdefinition(data,  callback);             },              function(data, uri, callback) {                 postdata(data, uri, callback);             },              function(syncuri, callback) {                 getsyncresponseinintervals(syncuri, callback);             }],          // bonus final callback function         function(err, status) {             if (err) {                 console.log(err);             }             console.log(status);             return;         }); }    function readfilesync_encoding(filename, encoding, callback) {       var content = fs.readfilesync(filename);       callback(null, iconvlite.decode(content, encoding));       return; } 

edit:

the problem in ide i've been using c9.io

when ran locally i've received error. interesting discovery.

you try checking existance first:

var fs = require('fs'); var content = '';  if(fs.accesssync(filename, fs.r_ok)) {  content = fs.readfilesync(filename); }  console.log(content); 

update: providing around async methods:

function waterfallmain(configfile){     async.waterfall([             function(callback){               fs.readfile(configfile, callback);             },             function(filedata, callback) {                //filedata contain contents of "configfile", if exists.                mainprocess(filedata, callback);             }     ], function(err, status) {         if (err) {             console.log(err);         }         console.log(status);     }); 

see fs.accesssync documentation more details.


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -