javascript node.js 让代码等待 fs.readFile 完成

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31762686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:20:03  来源:igfitidea点击:

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

javascriptnode.jsfs

提问by Deryckxie

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.

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


add explanation

添加说明

Actually I'm doing something like this: the function myfun is used for replace str you can see my code:

实际上我正在做这样的事情:函数 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
}

I need a return value in the replace function, so this is why I didn't use a callback function

我在替换函数中需要一个返回值,所以这就是我没有使用回调函数的原因

回答by Karl-Johan Sj?gren

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.

如果您需要同步执行,则应改用 fs.readFileSync() ( https://nodejs.org/api/fs.html#fs_fs_readfilesync_filename_options)。

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

回答by krl

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

您需要将回调传递给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 */} );

You need to invest some time into better understanding of asynchronous nature of JavaScript.

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

The problem with your code is that return stris outside of the readFilecallback, which means return strexecutes earlier than the readFilecallback gets called to set strto a meaningful value.

您的代码的问题在于它return strreadFile回调之外,这意味着return strreadFile调用回调以设置str为有意义的值之前执行。