0

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);}
    }); 

1 Answer 1

1

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");
}
Sign up to request clarification or add additional context in comments.

1 Comment

@FourCinnamon0 - Well, there's no array.push() in my code so I don't know exactly you're talking about. If you're doing .push() on the array variable in my code, then show exact what is in ./array.txt so we can see what you have. Also, do console.log(array) to see what Javascript thinks it is. FYI, this is base level debugging which you should be able to do yourself so you can present us with better information to help you quicker.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.