Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write an array to a file in nodejs and keep the square brackets?

I want to write a matrix to a .js file. When I use console.log(matrix) everything is fine but when I write it to the file it comes out differently.

var fs = require("fs");
var matrix = new Array(10);
for(var i=0;i<matrix.length;i++) matrix[i]=[];

for (var i = 0; i < 100 ; i++)
{ 
    var n = i%10;
    matrix[n].push(i);      
}

console.log(matrix);

//write it as a js array and export it (can't get brackets to stay)
fs.writeFile("./matrixtest.js", matrix, function(err) {
if(err) {
        console.log(err);
  } 
  else {
    console.log("Output saved to /matrixtest.js.");
    }
});     

So the console.log gives me [[0,10,20,30,...100],...,[1,11,21,31,...91]] and so on. But opening up matrixtest.js it's only this:

0,10,20,30,40,50...

All the numbers separated by commas with no brackets. How do I prevent it from converting to that format? Thank you.

like image 226
Henry Avatar asked Dec 15 '22 23:12

Henry


1 Answers

When you are writing an Array to a file, it is getting converted to a string as JavaScript cannot figure out how to write an array as it is. That is why it loses the format. You can convert an array to a string like this and check

var array = [1, 2, 3, 4];
console.log(array.toString());
// 1,2,3,4

So, to solve this problem, you might want to convert it to a JSON string like this

fs.writeFile("./matrixtest.js", JSON.stringify(matrix), function(err) {
    ...
}
like image 101
thefourtheye Avatar answered May 01 '23 07:05

thefourtheye