javascript - Async readFile module.exports in node.js -
i'm sorry for, might naive question, i`m trying figure out how node works, problem this:
what need send object/file fs.readfile through require , module.exports. have tried this
in 1 file (call app.js) code reading file:
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 other file, (call main.js) need use contents of file read readfile this
var file_importer = require('./app.js') file_importer.parsefile(real_path_to_file);
but if try console.log of last line undefined object. know because callback not execute before console.log i`m unsure how achieve communication.
so changed code little bit use callbacks. seems can't use "return" asyncronous function in module.exports. however, code bellow works expected. hope helps.
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
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); }); } } // shorter version exports.parsefile = function(file_path, callback) { fs.readfile(file_path.tostring(), 'utf-8', callback); }
Comments
Post a Comment