簡體   English   中英

如何將數組保存到文件中,然后再將其讀入nodejs / JavaScript中的數組變量中?

[英]How to save an array to file and later read it into an array variable in nodejs/JavaScript?

在nodejs中,我想將一些數據讀入一個數組,該數組先前已保存到文件中。 原始數據以數組的形式構造。 例:

let arr = [
  'id-001': [ '123', '246', '234' ],
  'id-002': [ '789', '235' ],
  ... and so on
];

像這樣保存:

fs.writeFileSync(dirpath + 'data.txt', arr);

這部分工作正常。 該文件包含以下字符串:

[
  'id-001': [ '123', '246', '234' ],
  'id-002': [ '789', '235' ],
  ... and so on
]

現在我以為我可以讀文件

let data = fs.readFileSync(filePath, 'utf8');

...這樣可行...

並做類似的事情

eval('let arr = ' + data);

要么

let arr = eval(data);

甚至

const vm = require('vm')
let arr = vm.runInNewContext(arr, {data})

還有更多。 什么都沒有。 它的行為很奇怪,似乎什么也沒發生,評估之后的代碼似乎沒有執行。 沒有錯誤。

有什么問題嗎? 有沒有更好的辦法?

您可以在讀取文件后使用JSON.parse解析文件內容,這應該可以使其工作。

此外,您將希望保留數據的JSON.stringify ed表示形式。

這是顯示整個過程的最小示例:

const fs = require('fs');

function write(array, path) {
    fs.writeFileSync(path, JSON.stringify(array));
}

function read(path) {
    const fileContent = fs.readFileSync(path);
    const array = JSON.parse(fileContent);
    return array;
}

write(['a', 'b'], '/my/path/test.txt');
const arr = read('/my/path/test.txt');
console.log(arr);

編寫文件時,應將其stringify

fs.writeFileSync(dirpath + 'data.txt', JSON.stringify(arr));

然后,您只需要將文件中的字符串數據parse回javascript對象

let data = JSON.parse(fs.readFileSync(filePath, 'utf8'));

首先糾正您的陣列並寫入/讀取文件

const fs = require('fs');

let dir = './data.txt';

let arr  = {'id-001': [ '123', '246', '234' ],
             'id-002': [ '789', '444' ]};

fs.writeFileSync(dir, JSON.stringify(arr));

let data = fs.readFileSync(dir, 'utf8');

console.log(data);

暫無
暫無

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

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