Lun Zhang Lun Zhang - 1 year ago 58
Node.js Question

Node export object with data from file

I am exporting the following object which initializes its data from a file

function wordsBox(){
this.words= {};

var w = new wordsBox();

fs.readFile('words.txt', function (err, data) {
w.words = JSON.parse(data.toString());

module.exports = w;

However, when I try to access the data from another file, its not reading.

var wordsBox = require('../db/word.reader');

The following comes out an empty object. Therefore, is there anyway to export the object after the fs has finished reading the data.

Answer Source

You have to use the sync version of fs.readFile:

var data = fs.readFileSync('words.txt')
w.words = JSON.parse(data.toString())

Requiring ("loading") other modules is a synchronous operation. If you want to populate your data from external resources, you have to do it synchronously too. However, I recommend to employ explicit (and optionally async) initialization of modules to leverage testing and avoid unexpected side effects.