Home > Software design >  Spawning Java File
Spawning Java File

Time:12-30

How can i spawn a java file while receiving stdout output?

I am trying to start a minecraft server file using child_process' spawn function, and attempting to get the output thats getting sent.

Heres what i've tried

var childP = require("child_process")

var server = childP.spawn("java", ["-jar", "Launch.jar", "nogui"])

server.on("spawn", () => {
    console.log("Server started")
})

server.on("message", (message) => {
    console.log(message)
})

server.on("error", (err) => {
    console.log(err)
})

server.on("disconnect", () => {
    console.log("Server disconnected");
})

server.on("exit", (code) => {
    console.log(`Server exited with code ${code}`)
})

CodePudding user response:

Easily done by just doing server.stdout.on("data"), should've looked more into the spawn event before asking the question :p

var childP = require("child_process")

var server = childP.spawn("java", ["-jar", "Launch.jar", "nogui"])


server.stdout.on("data", (data) => {
    console.log(data.toString().trim())
})

CodePudding user response:

To spawn a Java file and receive its standard output using the child_process module in Node.js, you can use the spawn function as follows:

`const { spawn } = require('child_process');

const javaProcess = spawn('java', ['-jar', 'minecraft_server.jar']);

javaProcess.stdout.on('data', (data) => { console.log(stdout: ${data}); });

javaProcess.stderr.on('data', (data) => { console.error(stderr: ${data}); });

javaProcess.on('close', (code) => { console.log(child process exited with code ${code}); });`

  • Related