0

I am trying to read the file, then create a temporary file then copy and replace the temporary file to the original file at the end.

Is it possible to do the following?

// read the original file then save it to temporary file
fs.readFile(originalPath, function (err, data) {
            var json = JSON.parse(data);
            json.items.push("sample item");
            fs.writeFileSync(tmpPath, JSON.stringify(json))
})

// copy the temporary file to the original file path
fs.readFile(tmpPath, (err, contents) => {
            var json = JSON.parse(contents);
            fs.writeFileSync(originalPath, JSON.stringify(json));
});

I am doing this to prevent the changes made to original file until the process has been completed.

It doesn’t seem to work due the the file is not physically saved when reading it.

Thanks.

Anonymous Asked question May 14, 2021