Home > front end >  Node script that reads and writes file (readFileSync and writeFileSync) reads the file different on
Node script that reads and writes file (readFileSync and writeFileSync) reads the file different on

Time:01-13

I am writing a node script that automates package updates within a package.json by reading the file, selecting the line with the package and giving the version a bump, and writing the new version of the file.

It runs fine when I run the script the first time. On the second run, readFileSync() gives a very different output, making the script break.

Here is the readFileSync function.

const data = fs.readFileSync("./package.json", {
  encoding: "utf8",
});

On the first run, data logs like this:

PS C:\Projects\update-version-test> node updateversion.js
Updating package: webpack , version: patch
data {
  "name": "update-version-test",
  "version": "1.0.0",
  "main": "index.js",
  "author": "eendkonijn",
  "license": "MIT",
  "dependencies": {
    "webpack": "^5.8.0"
  }
}

The script works as expected, and the webpack package is bumped to 5.8.1. If I run the script again, however, the data logs like this:

PS C:\Projects\update-version-test> node updateversion.js
Updating package: webpack , version: patch
} } "webpack": "^5.8.1"",-test",

The package.json file is intact but somehow readFileSync() doesn't seem to pick it up correctly the second run?

When I make a manual change, the script seems to be working again. But only the one time.

I have a reproduction here:

https://github.com/eendkonijn/update-version-test

CodePudding user response:

The problem is that you're trying to parse the json file using .split("\n") and later you assemble the resulting json content using .join(""). In the resulting file there will be no more line-breaks which is why your code does not work the second time.

Instead of manually parsing the json content, just parse it using JSON.parse, manipulate the webpack-property and finally overwrite the file content with the output of JSON.stringify. E.g:

const rawData = fs.readFileSync('./package.json', {
    encoding: 'utf8',
});

const parsedData = JSON.parse(rawData);
parsedData.dependencies.webpack = 'callFunctionToManipulateTheVersionHere()';

fs.writeFileSync('./package.json', JSON.stringify(parsedData, null, 4));
  • Related