簡體   English   中英

如何使用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) 更多信息在這里

讓我們假設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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM