Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy file content into a string?

Tags:

node.js

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?

like image 595
OldBoy Avatar asked Oct 18 '22 23:10

OldBoy


1 Answers

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);
});
like image 197
fos.alex Avatar answered Oct 24 '22 11:10

fos.alex