简体   繁体   中英

Display the dependencies from package.json

Is there a way we can display the version of Express, Jade, Stylus.. that we have installed in our nodejs. Capture the current version and display it in the browser.

Thanks

Basically a simple

$ npm ls

does what you want: It gives you a list of all installed modules, their versions, and their dependencies with the same info recursively.

As you have asked for a solution that works in your browser: The easiest solution will probably be to run that command as a child process from Node.js using the child_process module , and pipe the child's stdout property to the response stream of an http server.

Then you get the output of npm ls inside your browser.

The basic frame looks like this:

var spawn = require('child_process').spawn,
    http = require('http');

http.createServer(function (req, res) {
  var npm = spawn('npm', [ 'ls' ]);
  npm.stdout.pipe(res);
}).listen(3000);

Of course you can make it nicer, more comfortable, and so on :-)

Update from comments:

var npm = spawn('npm', [ 'ls', '--json' ]);

Although Golo Roden's reply describes a valid way, I think opening a separate process just to read a version is too much.

You are specifically asking about the version in package.json, so why don't you just read that file and parse it? I successfully managed to use the fs module for this. Here is my app:

var application_root = __dirname,
    express = require('express'),
    path = require('path'),
    fs = require('fs');

var app = express();

app.configure(function () {
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(app.router);
    app.use(express.static(path.join(application_root, "public")));
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.get('/api', function (req, res) {
    fs.readFile(application_root + '/package.json', function(err, fd) {
        console.log(err);
        console.log(fd);
        res.send('File data: ' + fd);
    });
});

app.listen(4242);

This will display the contents of the package.json file in your root folder, when you request the /api URL. If you only want the version of a specific dependency you can always query the properties of the fd object in the callback and display that.

Of course the disadvantage here is that this will always read the file rather than use the 'real' version from npm, but since your node application reads the file anyway, I don't see why not do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM