如何使用 javascript 将 .txt 文件的内容读取为数组?

How to read the content of a .txt file as an array with javascript?

我想将数组保存在 .txt 文件中,然后执行 fs.readFile 恢复它们并将它们保存在 javascript 的变量中。目前我的代码读取文件并将其保存为字符串。

保存在文件中的数组示例:

[[7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7],
[7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7],
[7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7],
[7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7],
[7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7],
[7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7]]

我的相关代码:

var data = fs.readFileSync('./Arrays/'+array1+'.txt', 'utf8');
console.log(data) // logs the array as a string
console.log(typeof data) // returns string

我要

var data = fs.readFileSync('./Arrays/'+array1+'.txt', 'utf8');

相当于

var data =  [[7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7],
    [7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7],
    [7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7],
    [7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7],
    [7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7],
    [7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7]];

我不确定这样做是否正确,因为它存在巨大风险,但您可以使用 eval(string) 并将其转换为数组。您也可以尝试拆分它,但需要更大的努力,因为它是一个二维数组。

编辑:您也可以尝试 JSON.parse(string)。更多信息 here

假设 myData.json 包含

[[3,4,5,6,7,8,9], [1,2,3,4,56,76]]

然后从另一个文件(假设在同一个文件夹中)

const myData = require('./myData.json')
// now consume it
console.log(myData)