How can I create a txt file that holds the contents of an array in JavaScript?

4k views Asked by At

I have several arrays that contain data that I would like to export, each array to a txt file, in order to be analyzed using MATLAB.

Let's say my array is:

var xPosition = [];

// some algorithm that adds content to xPosition

// TODO: export array into a txt file let's call it x_n.txt

It would be great to store each element of an array per line.

2

There are 2 answers

0
Ahmed Fasih On BEST ANSWER

The solution you found works, but here's how I'd have done it:

var fs = require('fs');
var xPosition = [1,2,3]; // Generate this
var fileName = './positions/x_n.txt';    
fs.writeFileSync(fileName, xPosition.join('\n'));

This uses node's synchronous file writing capability, which is ideal for your purposes. You don't have to open or close file handles, etc. I'd use streams only if I had gigabytes of data to write out.

0
lmiguelvargasf On

I have found a guide for the solution to my question in this post. The following code is what I ended up using:

var fs = require('fs');

var xPosition = [];

// some algorithm that adds content to xPosition

var file = fs.createWriteStream('./positions/x_n.txt');

file.on('error', function(err) { /* error handling */ });
xPosition.forEach(function(v) { file.write(v + '\n'); });
file.end();