90

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

8 Answers 8

140

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();
Sign up to request clarification or add additional context in comments.

4 Comments

Why not put file.end(); after the loop instead of testing the index?
Thanks! My arrays are in the order of 1000+ so this method works perfectly
odd, this is giving me error: TypeError: v.join is not a function, to troubleshoot, i logged typeof(v) within the loop and it is a string, coderade's solution doesn't seem to produce error though.
@user1063287 Double check that you're passing a multi-dimensional array (as in the OP)
58

Remember you can access good old ECMAScript APIs, in this case, JSON.stringify().

For simple arrays like the one in your example:

require('fs').writeFile(

    './my.json',

    JSON.stringify(myArray),

    function (err) {
        if (err) {
            console.error('Crap happens');
        }
    }
);

4 Comments

Not related to ArrayBuffers
if myArray is huge, JSON.stringify(myArray) will become a problem.
For better readability, you can use JSON.stringify(myArray, null, 1)
@ThịnhPhạm How huge is too huge?
33

To do what you want, using the fs.createWriteStream(path[, options]) function in an ES6 way:

const fs = require('fs');
const writeStream = fs.createWriteStream('file.txt');
const pathName = writeStream.path;
 
let array = ['1', '2', '3', '4', '5', '6', '7'];
  
// write each value of the array on the file breaking line
array.forEach(value => writeStream.write(`${value}
`));

// the finish event is emitted when all data has been flushed from the stream
writeStream.on('finish', () => {
   console.log(`wrote all the array data to file ${pathName}`);
});

// handle the errors on the write process
writeStream.on('error', (err) => {
    console.error(`There is an error writing the file ${pathName} => ${err}`)
});

// close the stream
writeStream.end();

Comments

19

A simple solution is to use writeFile :

require("fs").writeFile(
     somepath,
     arr.map(function(v){ return v.join(', ') }).join('\n'),
     function (err) { console.log(err ? 'Error :'+err : 'ok') }
);

7 Comments

If you do, don't forget the callback with err: nodejs.org/api/…
Not sure what's amiss, but my system pukes on this code as written. TypeError: v.join is not a function
Missing a ) after 'ok'
syntax error need to add arr.map(function(v){ return v.join(', ') >>}<here<< ).join('\n'),
@zipzit might be a bit late, but make sure items inside your array are arrays and not strings, otherwise, you can't use join() function on a string.
|
5
async function x(){
var arr = [ [ 1373628934214, 3 ],
[ 1373628934218, 3 ],
[ 1373628934220, 1 ],
[ 1373628934230, 1 ],
[ 1373628934234, 0 ],
[ 1373628934237, -1 ],
[ 1373628934242, 0 ],
[ 1373628934246, -1 ],
[ 1373628934251, 0 ],
[ 1373628934266, 11 ] ];
await fs.writeFileSync('./PATH/TO/FILE.txt', arr.join('\n'));
}

Comments

5

Try with this

await fs.writeFileSync('arreglo.txt', arreglo.join('\n '));

This code works for me

don't forget to import fs

import fs from 'fs';

2 Comments

Works great. Although the extra space isn't needed for the .join('\n '), it adds a space at the beginning of each line starting at line 2.
Yeah, i added this space to separate data but this doesn't work for me hahaha, just add a space, I'm glad it works for you
4

We can simply write the array data to the filesystem but this will raise one error in which ',' will be appended to the end of the file. To handle this below code can be used:

var fs = require('fs');

var file = fs.createWriteStream('hello.txt');
file.on('error', function(err) { Console.log(err) });
data.forEach(value => file.write(`${value}\r\n`));
file.end();

\r\n

is used for the new Line.

\n

won't help. Please refer this

1 Comment

That depends on the OS where the script is being run. For Linux \n is a valid newline. For Windows you need \r\n
1
const fs = require('fs');

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

const content = arr.map(item => item.join(', ')).join('\n');

const fp = 'output.txt';

fs.writeFileSync(fp, content, 'utf-8');

console.log('Array has been written to', fp);

1 Comment

Your answer could be improved by adding more information on what the code does and how it helps the OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.