node.js - node-csv-parser return value to variable -
i have next function:
//translate strings function translate(lng, str) { var translation = ''; csv().from(__dirname + '/../application/_common/lng/' + lng + '.csv', {delimiter: ';'}) .transform( function(row, index) { if(row[0] == str) { homecoming row[1]; } }) .on('data', function(data) { translation = data; }) .on('end', function() { homecoming translation; }); }
and want value found in csv variable this:
var translation = translate('en', 'translate_me');
the problem function not homecoming anything!
well, don't homecoming anything, homecoming things inner functions, outer function doesn't. if csv synchonous, this:
function translate(lng, str) { var translation = ''; csv().from(__dirname + '/../application/_common/lng/' + lng + '.csv', {delimiter: ';'}) .transform( function(row, index) { if(row[0] == str) { homecoming row[1]; } }) .on('data', function(data) { translation = data; }) .on('end', function() { homecoming translation; }); // returns inner function, has no effect. homecoming translation; // homecoming translation }
if csv _asynchronous, gets little bit harder. this:
function translate(lng, str, callback) // note parameter { var translation = ''; csv().from(__dirname + '/../application/_common/lng/' + lng + '.csv', {delimiter: ';'}) .transform( function(row, index) { if(row[0] == str) { homecoming row[1]; } }) .on('data', function(data) { translation = data; }) .on('end', function() { callback(translation); }); // phone call callback }
now phone call this:
var translation; translate('en', 'translate_me', function(val){ translation = val; });
node.js csv
No comments:
Post a Comment