{

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 fs module read json file.

Nodejs Get Version of package.json application

  • using require and import

if you are using the ES5 javascript version, use 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 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.