Node.js让代码等待fs. js文件.readFile已完成

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

本文关键字:js 文件 readFile 已完成 fs 等待 代码 Node      更新时间:2023-09-26

我在node.js文件系统中遇到了问题。这是我的代码。我的函数总是返回一个空字符串。我想知道是否有办法让我的函数停止执行,直到readFile方法完成。

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.
}

添加解释

实际上我是这样做的:函数myfun用于替换STR你可以看到我的代码:

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
}

我需要在替换函数中返回值,所以这就是为什么我没有使用回调函数

如果你需要同步,那么你应该使用fs.readFileSync() (https://nodejs.org/api/fs.html#fs_fs_readfilesync_filename_options)来代替。

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

为了在文件读取结束时从函数中获取数据,您需要像下面这样传递回调给myfun函数:

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 */} );

你需要花一些时间来更好地理解JavaScript的异步特性。

您的代码的问题是,return strreadFile回调之外,这意味着return str执行早于readFile回调被调用设置str为一个有意义的值。