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
node.js make code wait until the fs.readFile is completed
提问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 myfun
function 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 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.
您的代码的问题在于它return str
在readFile
回调之外,这意味着return str
在readFile
调用回调以设置str
为有意义的值之前执行。