OldBoy
OldBoy

Reputation: 110

How to copy file content into a string?

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?

Upvotes: 5

Views: 3711

Answers (1)

fos.alex
fos.alex

Reputation: 5627

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);
});

Upvotes: 3

Related Questions