how to kill command line process start with child_process nodejs - node.js

how can i stop it, it keep running after i stop nodejs. I try process.kill() but not working
const process = require('child_process')
const child = process.exec('ping 8.8.8.8 -t')
setTimeout(()=>child.kill(2),10000)
after a few hour reading nodejs docs, i found this for who have same my problem
const process = require('child_process')
const child = process.execFile('ping 8.8.8.8',['-t'],{cwd:'your working direct'})
setTimeout(()=>child.kill(2),10000)//now kill() working

I modified your code as below to flush out the error:
const process = require('child_process')
const child = process.spawn('ping 8.8.8.8 -t') // instead of process.exec
setTimeout(() => {
console.log(child.kill(2)) // --> false == failed
}, 10000);
child.on('error', (code, signal) => {
console.log(`${code}`) // --> Error: spawn ping 8.8.8.8 -t ENOENT
});
The ping command requires an argument after the -t ( as per terminal: ping: option requires an argument -- t

Related

Pushing process to background causes high kswapd0

I have a cpu-intensive process running on a raspberry pi that's executed by running a nodejs file. Running the first command (below) and then running the file on another tab works just fine. However when I run the process via a bash shell script, the process stalls.
Looking at the processes using top I see that kswapd0 and kworker/2:1+ takes over most of the cpu. What could be causing this?
FYI, the first command begins the Ethereum discovery protocol via HTTP and IPC
geth --datadir $NODE --syncmode 'full' --port 8080 --rpc --rpcaddr 'localhost' --rpcport 30310 --rpcapi 'personal,eth,net,web3,miner,txpool,admin,debug' --networkid 777 --allow-insecure-unlock --unlock "$HOME_ADDRESS" --password ./password.txt --mine --maxpeers 100 2> results/log.txt &
sleep 10
# create storage contract and output result
node performanceContract.js
UPDATE:
performanceContract.js
const ethers = require('ethers');
const fs = require('fs')
const provider = new ethers.providers.IpcProvider('./node2/geth.ipc')
const walletJson = fs.readFileSync('./node2/keystore/keys', 'utf8')
const pwd = fs.readFileSync('./password.txt', 'utf8').trim();
const PerformanceContract = require('./contracts/PerformanceContract.json');
(async function () {
try {
const wallet = await ethers.Wallet.fromEncryptedJson(walletJson, pwd)
const connectedWallet = wallet.connect(provider)
const factory = new ethers.ContractFactory(PerformanceContract.abi, PerformanceContract.bytecode, connectedWallet)
const contract = await factory.deploy()
const deployedInstance = new ethers.Contract(contract.address, PerformanceContract.abi, connectedWallet);
let tx = await deployedInstance.loop(6000)
fs.writeFile(`./results/contract_result_xsmall_${new Date()}.txt`, JSON.stringify(tx, null, 4), () => {
console.log('file written')
})
...
Where loop is a method that loops keccak256 encryption method. It's purpose is to test diffent gas costs by alternating the loop #.
Solved by increasing the sleep time to 1min. Assume it was just a memory issue that need more time before executing the contract.

How to allow Node.js child_process.execSync to run `scp -P 4422 root#myserver.com:/data/backups/...` without getting Permission Denied

I am running a simply Node.js process to backup my data everyday by using child_process.execSync to run:
scp -P 4422 root#myserver.com:/data/backups/dbs.zip /data/backups/dbs.zip
Notice if I run the above command directly, it will work. But when I do it in Node, the log I got is:
[2020-03-04 05:00:00] error downloading backup...Command failed:
Permission denied, please try again.
root#myserver.com: Permission denied (publickey,password).
Do I have to create a key file for Node.js' child_process to use when it fires scp? If so, how come if I run scp -i id_rsa.pem -P 4422 root#myserver.com:/data/backups/dbs.zip /data/backups/dbs.zip in Node.js it just stuck (like it even stops running any async actions such as appendFile. It also created a lot of processes called (node) and these processes cannot be killed.
const path = require('path');
const {
backupPath,
downloadPath
} = require('../../conf');
const keyPath = path.join(
__dirname,
'../../key/id_rsa.pem'
);
const downloadProcess = log => {
const { execSync } = require('child_process');
log('downloading backup...');
try {
const date = new Date();
const backupName = `db_${date.format('yyyy-MM-dd')}.tar.gz`;
const command = `scp -i ${keyPath} -P 4422 root#myserver.com:${backupPath}/${backupName} ${downloadPath}/${backupName}`;
log(`running command: ${command}`);
const stdout = execSync(command);
log(`downloaded backup ${backupName} at ${downloadPath}${'\n'}stdout:${'\n'}${stdout}`);
} catch (e) {
log(`error downloading backup...${e.message}`);
}
}
module.exports = downloadProcess;

Get terminals PID out of Node.js APP [duplicate]

How to get the process name with a PID (Process ID) in Node.JS program, platform include Mac, Windows, Linux.
Does it has some node modules to do it?
Yes, built-in/core modules process does this:
So, just say var process = require('process'); Then
To get PID (Process ID):
if (process.pid) {
console.log('This process is your pid ' + process.pid);
}
To get Platform information:
console.log('This platform is ' + process.platform);
Note: You can only get to know the PID of child process or parent process.
Updated as per your requirements. (Tested On WINDOWS)
var exec = require('child_process').exec;
var yourPID = '1444';
exec('tasklist', function(err, stdout, stderr) {
var lines = stdout.toString().split('\n');
var results = new Array();
lines.forEach(function(line) {
var parts = line.split('=');
parts.forEach(function(items){
if(items.toString().indexOf(yourPID) > -1){
console.log(items.toString().substring(0, items.toString().indexOf(yourPID)));
}
})
});
});
On Linux you can try something like:
var spawn = require('child_process').spawn,
cmdd = spawn('your_command'); //something like: 'man ps'
cmdd.stdout.on('data', function (data) {
console.log('' + data);
});
cmdd.stderr.setEncoding('utf8');
cmdd.stderr.on('data', function (data) {
if (/^execvp\(\)/.test(data)) {
console.log('Failed to start child process.');
}
});
On Ubuntu Linux, I tried
var process = require('process'); but it gave error.
I tried without importing any process module it worked
console.log('This process is your pid ' + process.pid);
One more thing I noticed we can define name for the process using
process.title = 'node-chat'
To check the nodejs process in bash shell using following command
ps -aux | grep node-chat
cf official documentation https://nodejs.org/dist/latest-v10.x/docs/api/process.html#process_process_pid
the require is no more needed.
The good sample is :
console.log(`This process is pid ${process.pid}`);

Node JS: Executing command lines and getting outputs asynchronously

How can I run a command line and get the outputs as soon as available to show them somewhere.
For example if a run ping command on a linux system, it will never stop, now is it possible to get the responses while the command is still processing ?
Or let's take apt-get install command, what if i want to show the progress of the installation as it is running ?
Actually i'm using this function to execute command line and get outputs, but the function will not return until the command line ends, so if i run a ping command it will never return!
var sys = require('sys'),
exec = require('child_process').exec;
function getOutput(command,callback){
exec(
command,
(
function(){
return function(err,data,stderr){
callback(data);
}
}
)(callback)
);
}
Try using spawn instead of exec, then you can tap into the stream and listen to the data and end events.
var process = require('child_process');
var cmd = process.spawn(command);
cmd.stdout.on('data', function(output){
console.log(output.toString()):
});
cmd.on('close', function(){
console.log('Finished');
});
//Error handling
cmd.stderr.on('data', function(err){
console.log(err);
});
See the Node.js documentation for spawn here: https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options

NODEJS process info

How to get the process name with a PID (Process ID) in Node.JS program, platform include Mac, Windows, Linux.
Does it has some node modules to do it?
Yes, built-in/core modules process does this:
So, just say var process = require('process'); Then
To get PID (Process ID):
if (process.pid) {
console.log('This process is your pid ' + process.pid);
}
To get Platform information:
console.log('This platform is ' + process.platform);
Note: You can only get to know the PID of child process or parent process.
Updated as per your requirements. (Tested On WINDOWS)
var exec = require('child_process').exec;
var yourPID = '1444';
exec('tasklist', function(err, stdout, stderr) {
var lines = stdout.toString().split('\n');
var results = new Array();
lines.forEach(function(line) {
var parts = line.split('=');
parts.forEach(function(items){
if(items.toString().indexOf(yourPID) > -1){
console.log(items.toString().substring(0, items.toString().indexOf(yourPID)));
}
})
});
});
On Linux you can try something like:
var spawn = require('child_process').spawn,
cmdd = spawn('your_command'); //something like: 'man ps'
cmdd.stdout.on('data', function (data) {
console.log('' + data);
});
cmdd.stderr.setEncoding('utf8');
cmdd.stderr.on('data', function (data) {
if (/^execvp\(\)/.test(data)) {
console.log('Failed to start child process.');
}
});
On Ubuntu Linux, I tried
var process = require('process'); but it gave error.
I tried without importing any process module it worked
console.log('This process is your pid ' + process.pid);
One more thing I noticed we can define name for the process using
process.title = 'node-chat'
To check the nodejs process in bash shell using following command
ps -aux | grep node-chat
cf official documentation https://nodejs.org/dist/latest-v10.x/docs/api/process.html#process_process_pid
the require is no more needed.
The good sample is :
console.log(`This process is pid ${process.pid}`);

Resources