2

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.

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
  • What environment is your JS running in: server (or similar), browser, …? – Nathan Tuggy Jun 12 '15 at 02:17
  • I am using NodeJS. My project consists on getting data from the AR.Drone 2.0 and compute other data. I'm sorry, but I have almost no experience with JS. I would like that the txt generated file be placed in the same directory where I am running the script. – lmiguelvargasf Jun 12 '15 at 02:18
  • 2
    Why not just use JSON? http://www.mathworks.com/matlabcentral/fileexchange/33381-jsonlab--a-toolbox-to-encode-decode-json-files-in-matlab-octave – Dan Jun 12 '15 at 06:34
  • 1
    @Dan's suggestion is good too: if you wind up needing more structured data to go from Node to Matlab, JSON is a good format. I've used JSONLab (Matlab) and it worked well. – Ahmed Fasih Jun 12 '15 at 23:28

2 Answers2

2

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();
Community
  • 1
  • 1
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
1

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.

Ahmed Fasih
  • 6,458
  • 7
  • 54
  • 95