javascript - How to execute the callback at the end of the function calling it? -
in node js application have function reads line line file, stores contents of file in array , calls callback function array passed callback.
function readfile(callback) { var fs = require('fs'), readline = require('readline'); var rd = readline.createinterface({ input: fs.createreadstream('./file.txt'), output: process.stdout, terminal: false }); var data = []; rd.on('line', function(line) { data.push(line); }); callback(data); }
the problem i'm facing readfile
running callback before file read , data
array filled. callback running empty array. how can make run once array filled? thanks.
readline has close event fired on "end"
so, code should be
function readfile(callback) { var fs = require('fs'), readline = require('readline'); var rd = readline.createinterface({ input: fs.createreadstream('./file.txt'), output: process.stdout, terminal: false }); var data = []; rd.on('line', function(line) { data.push(line); }).on('close', function () { callback(data); }); }
in es2015:
function readfile(callback) { var fs = require('fs'), readline = require('readline'); var rd = readline.createinterface({ input: fs.createreadstream('./file.txt'), output: process.stdout, terminal: false }); var data = []; rd.on('line', line => data.push(line)).on('close', () => callback(data)); }
or even
function readfile(callback) { var fs = require('fs'), readline = require('readline'), data = []; readline.createinterface({ input: fs.createreadstream('./file.txt'), output: process.stdout, terminal: false }) .on('line', line => data.push(line)) .on('close', () => callback(data)); }
but i'm not sure of 2 es2015 codes more readable
Comments
Post a Comment