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;
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;
I need the return value in the replace function, so I did not use the callback function
source share