1

I've create new java project with the following code which open the command line with the project path.In the java project I've added two files(under the root) app.js and package json,now I want to invoke this node app.js

I use the following code to open the command line which is working ok

Process newProc = Runtime.getRuntime().exec("cmd /c start cmd.exe");
OutputStream out = newProc.getOutputStream();

If I put in the command line manually(which is opened by the above program): node app.js The node js is starting ok. I want to do all of this with java code something like

Runtime.getRuntime().exec("cmd /c start cmd.exe node app.js");

and either with Runtime.getRuntime().exec("node app.js");

when I try this its not working...

My Java project look like followoing

myProj 
   src
   web
   app.js
   package.json

UPDATE This is the app.js file

var express = require('express');

var app = express();

app.get('/', function (req, res) {

    res.send("Test app running");
});


var server = app.listen(3005, function () {
        console.log("listen" + 3005)
    }
)

1 Answer 1

2

Try ProcessBuilder instead of Runtime:

ProcessBuilder pBuilder = new ProcessBuilder("C:\\Program Files\\nodejs\\node.exe", "C:\\temp\\app.js");
Process process = pBuilder.start();

process.waitFor();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks I try it but nothing happen please see my update and see the nodejs file ,I've created simple java program with this javascript file and put it under the root of the project and try to run it...
I've tried it by myself...see my update. Is it possible that you end the MainThread?

Your Answer

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