简体   繁体   English

在node.js中异步readFile module.exports

[英]Async readFile module.exports in node.js

I'm sorry for, what might easily be a naive question, but I`m trying to figure out how node works, especially for a problem like this: 我很抱歉,这可能很容易是一个幼稚的问题,但是我想弄清楚节点是如何工作的,尤其是对于这样的问题:

What I need do is to send an object/file from fs.readFile through require and module.exports. 我需要做的是通过require和module.exports从fs.readFile发送对象/文件。 This is what I have tried is this 这是我尝试过的

in one file (call it app.js) the code for reading a file: 在一个文件(称为app.js)中,用于读取文件的代码:

var fs = require('fs');
var file_contents = undefined;

var callback_reader = function(err, data) {
  if (err) return console.error(err);
  file_contents = data.toString().split('\n');
}

module.exports = {
  parseFile: function(file_path) {
    fs.readFile(file_path.toString(), 'utf-8', callback_reader);
  }
} 

and in some other file, (call it main.js) I need to use the contents of the file read by the readFile like this 在其他文件中(称为main.js),我需要像这样使用readFile读取的文件内容

var file_importer = require('./app.js')
file_importer.parseFile(real_path_to_file);

but if i try console.log of this last line I always get undefined object. 但是,如果我尝试最后一行的console.log,我总是会得到未定义的对象。 Now I know it is because callback does not execute before the console.log but I`m unsure how to achieve this communication. 现在我知道这是因为回调没有在console.log之前执行,但是我不确定如何实现这种通信。

So i changed your code a little bit to use callbacks. 所以我稍微修改了您的代码以使用回调。 It seems that you can't use "return" from asyncronous function in module.exports. 看来您不能在module.exports中使用异步函数中的“返回”。 However, the code bellow works as expected. 但是,下面的代码可以正常工作。 Hope it helps. 希望能帮助到你。

main.js main.js

var file_importer = require('./app.js')
file_importer.parseFile('./time.js', function(err, data){
    if(err) return console.log(err);
    console.log(data);
});

app.js app.js

var fs = require('fs');

module.exports = {
    parseFile: function(file_path, callback) {
        fs.readFile(file_path.toString(), 'utf-8', function(err, data) {
            if (err) return callback(err);
            callback(null, data);
        });
    }
}

// much shorter version
exports.parseFile = function(file_path, callback) {
    fs.readFile(file_path.toString(), 'utf-8', callback);
}

This is javascript work, it don't wait the callback was called to return. 这是javascript的工作,它不等待回调被调用返回。 You should do your console.log in your callback. 您应该在回调中执行console.log Like these : 像这些 :

fs.readFile(pathToFile, 'utf-8', function(err, data) {
  if (err) return err;
  console.log(data);
  // Continue your process here
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM