I understand CommonJS modules actually block as they load.
In some cases I wish to do particular work - loading and parsing config files for my app server - in a blocking way, i.e, since the app isn't usable until those files have loaded, only export once those async operations are complete.
Can I delay exporting until after an async operation in CommonJS? Or should I just use sync file reading / parsing methods instead?
You can export a function with a callback as parameter:
var fs = require('fs');
function parseContent(content) {
// do the content parsing
}
exports.getFileData = function (callback) {
fs.readFile('path/to/file', function (error, content) {
var data;
if (error) {
throw error;
} else {
data = parseContent(content);
callback(data);
}
});
};
usage:
moduleName.getFileData(function (data) {
// process data
});