javascript 如何将数组写入nodejs中的文件并保留方括号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22883743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:57:13  来源:igfitidea点击:

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

javascriptnode.js

提问by Henry

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.

我想将矩阵写入 .js 文件。当我使用 console.log(matrix) 时一切都很好,但是当我将它写入文件时,它会出现不同的结果。

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:

所以 console.log 给了我 [[0,10,20,30,...100],...,[1,11,21,31,...91]] 等等。但是打开 matrixtest.js 只有这样:

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.

所有数字以逗号分隔,不带括号。如何防止它转换为该格式?谢谢你。

采纳答案by thefourtheye

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

当您将数组写入文件时,它会被转换为字符串,因为 JavaScript 无法弄清楚如何按原样写入数组。这就是它丢失格式的原因。您可以将数组转换为这样的字符串并检查

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

所以,为了解决这个问题,你可能想把它转换成这样的 JSON 字符串

fs.writeFile("./matrixtest.js", JSON.stringify(matrix), function(err) {
    ...
}

回答by Patrick Evans

stringify it (JSON.stringify) before saving it then parse it (JSON.parse) when reading it back in.

在保存之前对其进行字符串化(JSON.stringify),然后在读回时解析它(JSON.parse)。

fs.writeFile("./matrixtest.js", JSON.stringify(matrix), function(err) {
  if(err) {
        console.log(err);
  } 
  else {
    console.log("Output saved to /matrixtest.js.");
  }
}); 

then when reading back in

然后在读回时

var matrix = JSON.parse(contents);

回答by Kruthika C S

The system doesn't know that you wanna store the array into the file with []. It just puts the contents of the array to the file.

系统不知道您要将数组存储到带有 [] 的文件中。它只是将数组的内容放入文件中。