{

Best ways to get package.json version in NodeJS with examples


This tutorial shows multiple ways to get a package.json version of a nodejs application.

There are multiple ways we can read the package.json file in Nodejs Application.

First Way, using require and import, Second-way using the fs module read json file. You can also check other posts on npm command deprecate option is deprecated

Nodejs Get the Version of the package.json application

  • using require and import

if you are using the ES5 javascript version, use the required keyword

  • import json file using require keyword and create a variable,
  • use the version variable directly using the imported variable
var packageJson = require('./package.json');
console.log(packageJson.version);

use import keyword for ES6 Ecmapscript6 version

  • import json file using import keyword,
  • use the version variable directly using the imported variable
import {version} from './package.json';
console.log(packageJson.version);

Output:

1.1.4
  • use readFileSync

It is an example of reading local json files using the fs module, readFileSync function.

  • import fs module
  • read json file using readFileSync function
  • Convert string into json using the JSON parse method

Here is an example code

fs = require('fs')
packagejson = JSON.parse(fs.readFileSync('package.json', 'utf8'))
console.log(packagejson.version)
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.