I am trying to execute a child process command to convert a file from a format to another using FFmpeg. I have FFmpeg installed in my system and in the same code I am able to successfully merge a video and a file using cp.spawn. The next step would be to convert the file in the desired format, but the process is immediately exiting with code 1, without giving any errors or outputs.
Here's the code:
const cp = require('child_process');
const ffmpeg = require('ffmpeg-static');
const process = cp.spawn(ffmpeg, [
'-loglevel', '8', '-hide_banner',
'-i', 'output.webm', "output.ogg",
], {
windowsHide: false,
});
process.on('error', (err) => {
console.log('Failed to start subprocess.', error);
});
process.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
process.stderr.setEncoding("utf8")
process.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
})
process.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
The file "output.webm" is in the current working directory. The only output that I'm getting is: child process exited with code 1, and nothing else happens.
Related
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});
});`
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}`);
});
Is it possible to run cmd.exe and execute some command with Electron.js?
If yes then how can I do this?
In your main.js file, you can put the following code:
//Uses node.js process manager
const electron = require('electron');
const child_process = require('child_process');
const dialog = electron.dialog;
// This function will output the lines from the script
// and will return the full combined output
// as well as exit code when it's done (using the callback).
function run_script(command, args, callback) {
var child = child_process.spawn(command, args, {
encoding: 'utf8',
shell: true
});
// You can also use a variable to save the output for when the script closes later
child.on('error', (error) => {
dialog.showMessageBox({
title: 'Title',
type: 'warning',
message: 'Error occured.\r\n' + error
});
});
child.stdout.setEncoding('utf8');
child.stdout.on('data', (data) => {
//Here is the output
data=data.toString();
console.log(data);
});
child.stderr.setEncoding('utf8');
child.stderr.on('data', (data) => {
// Return some data to the renderer process with the mainprocess-response ID
mainWindow.webContents.send('mainprocess-response', data);
//Here is the output from the command
console.log(data);
});
child.on('close', (code) => {
//Here you can get the exit code of the script
switch (code) {
case 0:
dialog.showMessageBox({
title: 'Title',
type: 'info',
message: 'End process.\r\n'
});
break;
}
});
if (typeof callback === 'function')
callback();
}
Now, you can execute arbitary command (the example is from windows command prompt, but the funtion is universal) by calling:
run_script("dir", ["/A /B /C"], null);
The parameters of your command are in fact an array ["/A /B /C"], and the last parameter is callback to be executed, you can provide null as parameter, if special callback function is not needed.
it is possible by using node child_process , You can use this function:
const exec = require('child_process').exec;
function execute(command, callback) {
exec(command, (error, stdout, stderr) => {
callback(stdout);
});
};
// call the function
execute('ping -c 4 0.0.0.0', (output) => {
console.log(output);
});
and there are many packages in npm for this topic to .
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)
I have a batch file which contains many jar files separated by semicolon :
%~d0
cd %~dp0
java -Xms256M -Xmx1024M -cp .;../lib/routines.jar;../lib/accessors-smart-1.1.jar;../lib/advancedPersistentLookupLib-1.0.jar; test_sample_connector.test_connector_0_1.TEST_connector --context=Default %*
When I call this batch in NodeJS I am getting the following error :
SyntaxError: Unexpected token %
But this batch file works fine if I run in command prompt.
Here is my node js code:
const { spawn } = require('child_process');
const bat = spawn('cmd.exe',['/c','../config/TEST_connector_0.1/TEST_connector/TEST_connector_run.bat']);
bat.stdout.on('data', (data) => {
console.log(data.toString());
});
bat.stderr.on('data', (data) => {
console.log(data.toString());
});
bat.on('exit', (code) => {
console.log(`Child exited with code ${code}`);
});