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}`)
})
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())
})
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
Following the official node documentation of net and child_process modules, I archived this: a server that spawns a child and connect through net module. But the connection is intermittent. The code is self explanatory, but I've add details in the code comments:
// server.js
const childProcess = require('child_process').fork('child.js');
const server = require('net').createServer((socket) => {
console.log('got socket connection'); // this callback is intermitent
socket.on('data', (stream) => {
console.log(stream.toString());
})
});
server.on('connection', () => {
console.log('someone connected to server'); // this is running only if the code above runs (but its intermitent)
});
server.on('listening', () => {
console.log('server is listening'); // this is the first log to execute
childProcess.send('server', server); // send the server connection to forked child
});
server.listen(null, function () {
console.log('server listen callback'); // this is the second log to execute
});
// child.js
console.log('forked'); // this is the third log to execute
const net = require('net');
process.on('message', (m, server) => {
if (m === 'server') {
const socket = net.connect(server.address());
socket.on('ready', () => {
console.log('child is ready'); // this is the fourth log to execute
socket.write('child first message'); // this is always running
})
}
});
the expected log when execute node server is:
server is listening
server listen callback
forked
child is ready
got socket connection
someone connected to server
child first message
but as the socket callback (at createServer) is intermitent, we get this 50% of times:
server is listening
server listen callback
forked
child is ready
IDK what to do anymore, already tried everything I could... What am I doing wrong?
Just found what was the problem... when I read the documentation I misunderstood that literally the net server is being sent to the child process to share the "connections" to divide the processing in more than one process, and what I was trying to archive was just an 2 way communication with the forked child. I'll let this answer here if someone arrive at the same problem as me. This is the final code:
// server.js
const childProcess = require('child_process').fork('child.js');
const server = require('net').createServer((socket) => {
console.log('got socket connection');
socket.on('data', (stream) => {
console.log(stream.toString());
})
});
server.on('connection', () => {
console.log('someone connected to server');
});
server.listen(null, function () {
childProcess.send(server.address());
});
// child.js
console.log('forked');
const net = require('net');
process.on('message', (message) => {
if (message.port) {
const socket = net.connect(message);
socket.on('ready', () => {
console.log('child is ready');
socket.write('child first message');
})
}
});
I would like to send "Hello world" from one nodejs server to another using node-serialport. I have verified that the radios connecting the two are connected and sending info because they keep displaying buffer information after running my current code.
here is what I have so far.
server1
// Import dependencies
const SerialPort = require("serialport");
const Readline = require("#serialport/parser-readline");
var sf = require('sf');
//SerialPort.list(function (err, results) {
// if (err) {
// throw err;
// }
SerialPort.list().then(ports => {
ports.forEach(function(port) {
console.log(port.path);
console.log(port.pnpId);
console.log(port.manufacturer);
});
});
// Defining the serial port
const port = new SerialPort('COM3',{baudRate: 9600}, function (err) {
if (err) {
return console.log('Port Error: ', err.message)
}
})
port.write('main screen turn on', function(err) {
if (err) {
return console.log('Error on write: ', err.message)
}
console.log('message written')
})
// Read data that is available but keep the stream in "paused mode"
port.on('readable', function () {
console.log('Data:', port.read())
})
// Switches the port into "flowing mode"
port.on('data', function (data) {
console.log('Data:', data)
})
// Pipe the data into another stream (like a parser or standard out)
const lineStream = port.pipe(new Readline())
lineStream.on('data', console.log)
server 2
// Import dependencies
// in Ubuntu need to run command: sudo chmod 666 /dev/ttyS0 to open port for use
const SerialPort = require("serialport");
const Readline = require("#serialport/parser-readline");
var stoploop = true;
// Defining the serial port
const port = new SerialPort('/dev/ttyUSB0', function (err) {
if (err) {
return console.log('Error: ', err.message)
}
})
port.write('chicken butt', function(err) {
if (err) {
return console.log('Error on write: ', err.message)
}
console.log('message written')
})
// port.write("hello?");
// Read data that is available but keep the stream in "paused mode"
port.on('readable', function () {
console.log('Data:', port.read())
})
// Switches the port into "flowing mode"
port.on('data', function (data) {
console.log('Data:', data)
})
// Pipe the data into another stream (like a parser or standard out)
const lineStream = port.pipe(new Readline())
any help or even an example of how to send hello world between the two would be greatly appreciated! please let me know if any more info is needed.
edit : I recently tried doing something like
port.on('data', (data) => {
try {
console.log(data.toString());
} catch (err) {
console.log('Oops');
}
});
this is taking data that used to appear as <buffer # # # # #> and turning it into an odd string like "(
)))) ) ) )))
!)☺)!))) ) )
)(☺!�"
I found the answer myself!
I was using the wrong baudRate, and also needed to stringify the data being sent as a JSON string
I am trying to get the lines a ('never ending') python script puts into stdout. But currently my code would only log something to the console when the python process exits. Is there a way I can get the 'live' output of the python script line by line?
spawn_child.js:
let execFile = require("child_process").execFile;
var child = execFile("python3", ["PATH_TO_FILE"]);
child.stdout.on("data", data=>{
console.log(data.toString());
});
child.stderr.on("data", data=>{
console.log(data.toString());
});
child.on("exit", code=>{
console.log("Child exited with code "+code);
});
The python file:
from time import sleep
while True:
sleep(3)
print("test")
Edit: It works when using a nodejs script instead of a python script
change python script to
import time
import sys
while True:
time.sleep(1)
print("test")
sys.stdout.flush()
and increase the buffer size of the child process
const child = execFile("python", ["./runner.py"], {
detached: true,
maxBuffer: 10 * 1024 * 1024 * 1024
});
or you can do it without the flushing to stdout with python-shell
const { PythonShell } = require('python-shell');
let pyshell = new PythonShell('runner.py');
pyshell.on('message', function (message) {
console.log(message);
});
pyshell.end(function (err, code, signal) {
if (err) throw err;
console.log('The exit code was: ' + code);
console.log('The exit signal was: ' + signal);
console.log('finished');
});
Use spawn instead of execFile, dont forget options shell and stdio.
const spawn = require("child_process").spawn;
const child = spawn("python3", ["file.py"], {shell: true, stdio: 'inherit'});
child.on('data', function(data) {
console.log(data);
});
child.on('close', function(code) {
console.log('Child process exited with exit code '+code);
});
You can also add cwd option.
Was trying to implement something similar inside a NextJS application and wanted live output from my python script and using python-shell had the same issue that it was only giving me output when the process existed and I ended up using node-pty instead which worked as expected:
import { spawn } from "node-pty"
const pyProcess = spawn("python", ["path/to/python/script"], {
name: 'xterm-color',
cols: 80,
rows: 30,
cwd: process.cwd(),
});
pyProcess.on('data', function (data: { toString: () => any; }) {
console.log(data.toString());
});
pyProcess.on('exit', (code: any) => {
console.log(`child process exited with code ${code}`);
});
I am working on a loopback project where I need to run a background job. Spawn node child process. Since I am beginner, documentation is little confusing. https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options
parent.js
const path = require("path");
const spawn = require('child_process').spawn;
let child = spawn('node', [__dirname + '../../worker/worker.js']);
child.stdout.on('data', function (data) {
console.log('data available ' + data);
});
child.stderr.on('data', function (data) {
console.log('There was an error: ' + data);
});
worker.js
function jobListener() {
let query = { jobname: "countProvider"}
let result = Job.findOne({ where: query }, function(err, instance) {
if(err) {
console.log('Error', err);
}
// console.log(instance);
});
while (!result) {
console.log(result);
// await sleep(5000);
console.log('checking for job in mongodb with a delay of 5 seconds');
}
if(result) {
fetchProcedureRequest();
}
}
jobListener();
function fetchProcedureRequest() {
console.log('Fetching pREquest');
}
What I am trying to achieve is I am getting the data in child process. But how can I close/exit the process when data is available in parent. Somebody please help and any suggestion will be really appreciated.
May be you can use this, found here How to kill childprocess in nodejs?
var proc = require('child_process').spawn('mongod');
proc.kill('SIGINT');
I am trying to kill a child process I have running within my server. Basically the child process runs johnny-five code I've written in an online terminal in React to my server. When I run the child process, the code works great but if I want to kill the child process I cant do so without stopping the server. I've tried doing so with Control-C and .exit() but neither seem to work.
codeRouter
.post('/codeAPI', (req, res) => {
console.log(req.body)
let fileName = `johnnyFiles/${req.body.currentFile}`
fs.writeFileSync(fileName, req.body.currentCode, (err) => {
if (err) throw err
})
let id = shortid.generate()
let fileObject = {
fileName: req.body.currentFile,
fileContents: req.body.currentCode,
ID: id
}
data = [fileObject, ...data]
fs.writeFileSync('data/fileData.json', JSON.stringify(data), (err) => {
if (err) throw err
})
res.json(data)
///////////////////////////////////////////
let nodeSpawn = spawn('node', [fileName], {
//detached: true,
shell: true
})
nodeSpawn.stdout.on('data', (data) => {
console.log("OUTPUT", data.toString())
})
nodeSpawn.stderr.on('data', (data) => {
console.log("ERRORS", data.toString())
})
nodeSpawn.on('exit', (code) => {
console.log(`Child exited with code ${code}`)
nodeSpawn.kill('SIGINT')
})
})
`
You can use the linux command line.
To see the running processes use the command, use:
pgrep node
To kill the process you can use:
kill <pid>
Or to force the shutdown
kill -9 <pid>
Or if you want kill all node processes
kill $(pgrep node)