in nodejs I want to read some data into an array which has been saved previously to file. The original data is structured in an array. Example:
let arr = [
'id-001': [ '123', '246', '234' ],
'id-002': [ '789', '235' ],
... and so on
];
It is saved like this:
fs.writeFileSync(dirpath + 'data.txt', arr);
This part works fine. The file contains this string:
[
'id-001': [ '123', '246', '234' ],
'id-002': [ '789', '235' ],
... and so on
]
Now I thought I could just read the file
let data = fs.readFileSync(filePath, 'utf8');
...that works...
and do something like
eval('let arr = ' + data);
or
let arr = eval(data);
or even
const vm = require('vm')
let arr = vm.runInNewContext(arr, {data})
and some more. Nothing works. It behaves strange, just nothing seems to happen, code after the eval seems not to be executed. No errors.
What may be wrong? Is there a better way?
You can parse the file content using JSON.parse
after reading it, that should make it work.
Also, you'll want to persist a JSON.stringify
ed representation of your data.
Here's a minimum example that shows the whole process:
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);
When you write the file you should stringify
it:
fs.writeFileSync(dirpath + 'data.txt', JSON.stringify(arr));
Then you simply need to parse
the string data from the file back to a javascript object
let data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
Correct your array 1st and write/read the file
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.