Node.js make code until fs.readFile completes

I am having a problem in the node.js. file system here is my code. my function always returns an empty string. I'm curious, one way or another, for my function to stop executing until the readFile method completes.

var fs = require('fs'); function myfun(filePath){ var str = ''; fs.readFile(filePath, function(err, data){ if(err) throw err; str = data; }); return str; //here, the variable str always return '' because the function doesn't wait for the readFile method complete. } 

add explanation

Actually I am doing something like this: myfun function is used to replace str, you can see my code:

 function fillContent(content) { var rex = /\<include.*?filename\s*=\s*"(.+?)"\/>/g; var replaced = fileStr.replace(rex, function (match, p1) { var filePath = p1 var fileContent = ''; fs.readFile(filePath, function (err, data) { if (err) { throw err; } fileContent = data; }); return fileContent; }); return replaced;// here, the return value is used for replacement } 

I need the return value in the replace function, so I did not use the callback function

+4
source share
2 answers

You need to pass a callback to the myfun function, as shown below, to return data from the function when the file is finished reading.

 var fs = require('fs'); function myfun(filePath, cb){ var str = ''; fs.readFile(filePath, 'utf8', function(err, data){ if(err) throw err; cb(data); }); } // call it like this myfun('some_path', function(data) { /* use returned data here */} ); 

You need to spend some time getting a better understanding of the asynchronous nature of JavaScript.

The problem with your code is that return str is outside the readFile , which means that return str is executed before the readFile is called to set str to a meaningful value.

+4
source

If you need to do this synchronously, you should use fs.readFileSync () instead ( https://nodejs.org/api/fs.html#fs_fs_readfilesync_filename_options ).

 var fs = require('fs'); function myfun(filePath){ return fs.readFileSync(filePath); } 
+2
source

All Articles