node.js make code wait until the fs.readFile is completed

24,886

Solution 1

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

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

Solution 2

You need to pass a callback to myfun function as below in order to get back data from the function when file reading is over:

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 invest some time into better understanding of asynchronous nature of JavaScript.

The problem with your code is that return str is outside of the readFile callback, which means return str executes earlier than the readFile callback gets called to set str to a meaningful value.

Share:
24,886
Deryckxie
Author by

Deryckxie

Updated on February 11, 2020

Comments

  • Deryckxie
    Deryckxie over 4 years

    I got a problem in node.js file system. here is my code. my function always return a empty string. I'm wondering is there anyway to make my function stop execute until readFile method is completed.

    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'm doing something like this: the function myfun is used for 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 a return value in the replace function, so this is why I didn't use a callback function

    • Pointy
      Pointy almost 9 years
      @GopinathShiva puting return str; inside the callback will not do any good. OP you're looking for fs.readFileSync().
    • Gopinath Shiva
      Gopinath Shiva almost 9 years
    • robertklep
      robertklep almost 9 years
      If you really need to use it with .replace(), you should use fs.readFileSync().
    • Deryckxie
      Deryckxie almost 9 years
      thank robertklep, I'm wondering whether I used fs in a replace function is a good way
  • adelphus
    adelphus almost 9 years
    This is the way to go with nodejs - although I would probably add the utf8 encoding parameter because it looks like the OP is expecting a string to be returned.