Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify if Java is installed from Node.js

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!

like image 532
Formiga Avatar asked Mar 21 '23 19:03

Formiga


1 Answers

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);
})
like image 196
Sudsy Avatar answered Apr 02 '23 10:04

Sudsy