Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js - how to write an array to file

I have a sample array as follows

var arr = [ [ 1373628934214, 3 ],   [ 1373628934218, 3 ],   [ 1373628934220, 1 ],   [ 1373628934230, 1 ],   [ 1373628934234, 0 ],   [ 1373628934237, -1 ],   [ 1373628934242, 0 ],   [ 1373628934246, -1 ],   [ 1373628934251, 0 ],   [ 1373628934266, 11 ] ] 

I would like to write this array to a file such as I get a file as follows

1373628934214, 3  1373628934218, 3 1373628934220, 1 ...... ...... 
like image 242
dopplesoldner Avatar asked Jul 12 '13 11:07

dopplesoldner


People also ask

How do I write an array of data into a file?

Since the size of the data is fixed, one simple way of writing this entire array into a file is using the binary writing mode: FILE *f = fopen("client. data", "wb"); fwrite(clientdata, sizeof(char), sizeof(clientdata), f); fclose(f);

How do I import an array into node js?

You can define your array on the exports object in order to allow to import it. You could create a . json file as well, if your array only contains simple objects. If you require a module (for the first time), its code is executed and the exports object is returned and cached.


1 Answers

If it's a huuge array and it would take too much memory to serialize it to a string before writing, you can use streams:

var fs = require('fs');  var file = fs.createWriteStream('array.txt'); file.on('error', function(err) { /* error handling */ }); arr.forEach(function(v) { file.write(v.join(', ') + '\n'); }); file.end(); 
like image 157
mak Avatar answered Sep 20 '22 20:09

mak