4

I'm building an application that uses Java inside Node.js. I made a Function to check the Java version:

function javaversion() {
    var spawn = require('child_process').spawn('java', ['-version']);
    spawn.stderr.on('data', function(data) {
        data = data.toString().split('\n')[0];
        var javaVersion = new RegExp('java version').test(data) ? data.split(' ')[2].replace(/"/g, '') : false;
        if (javaVersion != false) {
            // TODO: We have Java installed
        } else {
            // TODO: No Java installed
        }
    });
}

But for systems that Java is not installed, Node.js is throwing ENOENT error, because the module "child_process" just can't spawn the process. How can I verify if Java is installed from Node.js?

I appreciate your help!

3
  • have you considered checking for an environment variable like classpath or ...? And then looking for the binary? Commented Nov 1, 2013 at 21:42
  • @WiredPrairie, Yes, I considered, but it is not a good idea to all systems. For example, in OS X 10.8, CLASSPATH is not set. I solved the problem handling the error of not spawning the process, like Sudsy suggested. Thank you. Commented Nov 2, 2013 at 0:09
  • I've got Java installed (per the Windows installer), but it's not in the path, so this method fails completely. So, doesn't really seem like a good solution for "all systems." Commented Nov 2, 2013 at 1:40

1 Answer 1

7

What about this?

function javaversion(callback) {
    var spawn = require('child_process').spawn('java', ['-version']);
    spawn.on('error', function(err){
        return callback(err, null);
    })
    spawn.stderr.on('data', function(data) {
        data = data.toString().split('\n')[0];
        var javaVersion = new RegExp('java version').test(data) ? data.split(' ')[2].replace(/"/g, '') : false;
        if (javaVersion != false) {
            // TODO: We have Java installed
            return callback(null, javaVersion);
        } else {
            // TODO: No Java installed

        }
    });
}

javaversion(function(err,version){
    console.log("Version is " + version);
})
Sign up to request clarification or add additional context in comments.

2 Comments

How can I check if JDK is installed or not ? If not installed, install it.
It fails on openjdk. Change the regex from 'java version' to '(java|openjdk) version' to work on openjdk.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.