I am trying to "translate" my old scripts done in Ruby to node.js. One of them is about CSV parsing, and I am stuck at step one - load file into a string.
This prints content of my file to the console:
fs = require('fs');
fs.readFile("2015 - Best of.csv", 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
console.log(data);
});
but for some reason I can't catch data into variable:
fs = require('fs');
var x = "";
fs.readFile("2015 - Best of.csv", 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
x = x + data;
});
console.log(x);
How do I store (function's) 'data' variable into (global) 'x' variable?
It is working.
The problem is you are logging x before it gets filled. Since the call is asynchronous, the x variable will only have the contents of the string inside the function.
You can also see the: fs.readFileSync function.
However, I would recommend you get more confortable with node's async features.
Try this:
fs = require('fs');
var x = "";
fs.readFile("2015 - Best of.csv", 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
x = x + data;
console.log(x);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With