Below you will find how to replace a line in a text file for reference and a good one, too. But you really should not use this method to update a JSON file. What you should want, is parse the JSON data, so you can edit the data and save the edited data in a text file.
So, we are not speaking about lines here, but about data, that has been serialized into the JSON format. The stored data must be updated.
There are a lot of problems, which editing a JSON files line by line could cause. In the end, the file could get corrupted and get your system into an undesirable state.
Both of the implementations below are synchronous, as this might be easier to understand for a beginner.
Please remember to always create a backup, when working with production data.
How to do it
This script will parse a json file, change the secretCode and save it back into the same file.
var fs = require('fs');
function replaceDataInJsonFile(filePath, propertyName, newData) {
// Read the complete file content into a tring.
var fileText = fs.readFileSync(filePath, 'utf-8');
// Create an object containing the data from the file.
var fileData = JSON.parse(fileText);
// Replace the secretCode in the data object.
fileData[propertyName] = newData;
// Create JSON, containing the date from the data object.
fileText = JSON.stringify(fileData, null, " ");
// Write the updte file content to the disk.
fs.writeFileSync(filePath, fileText, 'utf-8');
}
// Call the function above.
replaceDataInJsonFile('test.json', 'secretCode', 2233);
How not to do it
This script will overwrite the fourth line of the utf-8 encoded file test.json. The test.json file is located in the execution directory of Node.js.
var fs = require('fs');
function replaceLineInFile(filePath, lineIndex, newLineText) {
// Read the complete file content into a tring.
var fileText = fs.readFileSync(filePath, 'utf-8');
// Get line break chars.
var lineBreakChars = '\r\n';
if (fileText.indexOf(lineBreakChars) > -1) {
lineBreakChars = '\n';
}
// Split the file content into an array of lines.
var fileLines = fileText.split(lineBreakChars);
// Overwrite a line from the array of lines.
fileLines[lineIndex] = newLineText;
// Join the line array elements into a single string again.
fileText = fileLines.join(lineBreakChars);
// Write the updte file content to the disk.
fs.writeFileSync(filePath, fileText, 'utf-8');
}
// Call the function above.
replaceLineInFile('test.json', 3, ' "secretCode": 2233');
Input/Output File
Both scripts may take the following lines in an input file, update the data and write the updated data back into the file.
The content of test.json, before the script has been executed.
{
"name": "James",
"birthday": "March 22",
"secretCode": 16309
}
The content of test.json, after executing node myscript.js
, with myscript.js
containing the code from above.
{
"name": "James",
"birthday": "March 22",
"secretCode": 2233
}