Node Reading from Package.json

Posted on Monday, May 11, 2015



How do you simply read data from your package.json file?
Turn out its real easy.   Poking around I found this post 





Here my package.json file


{
  "name": "MyApp",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "private": "true",
  "scripts": {
    "test": "mocha --recursive test",
    "start-dev": "nodemon server.js",
    "gen-idea": "jetbrains init"
  },
  "author": "Patrick Bailey",
  "license": "ISC",
  "devDependencies": {
    "chai": "^2.2.0",
    "chai2-json-schema": "^1.2.0",
    "jetbrains": "^0.1.2",
    "mocha": "^2.2.4",
    "nodemon": "^1.3.7",
    "superagent": "^1.1.0"
  },
  "dependencies": {
    "config": "^1.12.0",
    "express": "^4.12.3"
  }
}




Here is my app,js 




var express = require('express');
var config = require('config');
var pkgJSON = require('./package.json');

var app = express();
var server;

var start = exports.start = function start(port, callback) {
   
server = app.listen(port, callback);
};

var stop = exports.stop = function stop(callback) {
   
server.close(callback);
};

app.get('/package-info', function sendResponse(req, res) {
    res.
json(
        {
           
"name": pkgJSON.name,
           
"version": pkgJSON.version,
           
"devDependencies": pkgJSON.devDependencies,
           
"nodemon-script": pkgJSON.scripts["start-dev"],
           
"scripts-test" : pkgJSON.scripts.test
       
});
});




All you have to do is require the package.json file.  Turns out that the require will parse the JSON for you so no need to parse it yourself J




var pkgJSON = require('./package.json');


One issue I ran into was a JSON name that had a "-" dash in it.  You can't access it directly.




"nodemon-script": pkgJSON.scripts.start-dev,


This above won't work


So you have to put in in brackets like this.




 
"nodemon-script": pkgJSON.scripts["start-dev"],




If I run this and open http://localhost:3000/package-info I get







Pretty simple!



References

[1]        Is there a way to get version from package.json in nodejs code?

                Accessed 5/2015 

No comments:

Post a Comment