'How to update version in package.json [duplicate]

I need to update the version by reading it from package J SON file which will be 1.1.1. After reading i need to append the build number with it like 1.1.1-1 and then i want to update the version field within the package J SON file. How i can achieve it?

Thanks



Solution 1:[1]

You can use fs.readFile() and fs.writeFile() to read and edit the package.json file.

append-build-to-version.js:

var fs = require('fs');

fs.readFile('./package.json', (err, data) => {
    if (err) throw err;

    var packageJsonObj = JSON.parse(data);
    var build = 5; // get this from somewhere or increment the last char
    var versionNumber = packageJsonObj.version;
    packageJsonObj.version = `${versionNumber}-${build}`;
    packageJsonObj = JSON.stringify(packageJsonObj);

    fs.writeFile('./package.json', packageJsonObj, (err) => {
        if (err) throw err;
        console.log('The file has been saved!');
    });
});

package.json:

{
    "name": "teststackoverflow",
    "version": "1.0.0-5",
    "description": "",
    "main": "router.js",
    "dependencies": {},
    "devDependencies": {},
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "author": "",
    "license": "ISC"
}

More info on fs.readFile() and fs.writeFile() can be found in the Node.js documentation.

Solution 2:[2]

You can use npm version <YOUR VERSION>

To increment versions use:

npm version major for major versions and

npm version minor For minor versions and

npm version patch For bug fixes

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 kittu