fourk
fourk

Reputation: 332

How do I read an array in a file to an array variable in node.js?

I have an array like so: [1,2,3] and I want to write it to a file. Then I want to read it from that file (after restart of my node process) and write it into an array variable in node. Here is my code:

var array = fs.readFileSync("./array.txt")
array.push(4)
fs.writeFile("./array.txt", array, function(err) {
        if(err) {return console.log(err);}
    }); 

Upvotes: 0

Views: 768

Answers (1)

jfriend00
jfriend00

Reputation: 707258

You have to decide what storage format you want to use in your text file. A Javascript object is an internal format. A typical format to use for Javascript objects is JSON. Then, you need to convert TO that format when saving and parse FROM that format when reading.

So, in Javascript, JSON.stringify() converts a Javascript object/array into a JSON string. And, JSON.parse() converts a JSON string into a Javascript object/array.

You can write your array in JSON using this:

fs.writeFile("./array.txt", JSON.stringify(array), function(err) {
    if(err) {return console.log(err);}
}); 

And, you can read in JSON like this:

try {
    let array = JSON.parse(fs.readFileSync("./array.txt"));
    // use your array here
} catch(e) {
    console.log("some problem parsing the JSON");
}

Upvotes: 1

Related Questions