node.jsmatlabserializationar.drone

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


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.


Solution

  • 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.