Each language has its own advantages. It combines each other with its own strengths to execute the program more efficiently or uses which implementation method is simpler. nodejs uses child processes to call system commands or files. The document is shown at http://nodejs.org/api/child_process.html. The NodeJS subprocess provides important interfaces for interacting with the system. Its main APIs include: standard input, standard output and standard error output interfaces.
The NodeJS child process provides important interfaces for interacting with the system, and its main APIs are:
Interfaces for standard input, standard output and standard error output
child.stdin Get standard input
child.stdout Gets standard output
child.stderr Gets standard error output
Get the PID of the child process: child.pid
Provide a method to generate child processes: child_process.spawn(cmd, args=[], [options])
Provide a method to directly execute system commands: child_process.exec(cmd, [options], callback)
Provide a method to call the script file: child_process.execFile(file, [args], [options], [callback])
Provide a method to kill the process: child.kill(signal='SIGTERM')
It's very interesting to use examples to experience it, haha~~
1. Use the child process to call system commands (get system memory usage)
Create a new nodejs file named cmd_spawn.js, the code is as follows:
The code copy is as follows:
var spawn = require('child_process').spawn;
free = spawn('free', ['-m']);
// Capture standard output and print it to the console
free.stdout.on('data', function (data) {
console.log('standard output:/n' + data);
});
// Capture standard error output and print it to the console
free.stderr.on('data', function (data) {
console.log('standard error output:/n' + data);
});
// Register child process shutdown event
free.on('exit', function (code, signal) {
console.log('child process eixt ,exit:' + code);
});
Here is the result of running the script and directly running the command 'free -m', exactly the same:
2. Execute system commands (child_process.exec())
I still use this very often, and the function feels a little more powerful than the above. For example, I like to pay attention to the weather. Now I want to curl the weather interface to return data in json format. Maybe I want to operate it, but I will print it here and not operate it.
Create a new nodejs file named cmd_exec.js:
The code copy is as follows:
var exec = require('child_process').exec;
var cmdStr = 'curl http://www.weather.com.cn/data/sk/101010100.html';
exec(cmdStr, function(err,stdout,stderr){
if(err) {
console.log('get weather api error:'+stderr);
} else {
/*
The content of this stdout is the thing I curl above:
{"weatherinfo":{"city":"Beijing","cityid":"101010100","temp":"3","WD":"Northwest wind","WS":"level 3","SD":"23%","WSE":"3","time":"21:20","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB","njd":"No live yet","qy":"1019"}}
*/
var data = JSON.parse(stdout);
console.log(data);
}
});
Let's experience the result of curl directly and running scripts is the same:
3. Call the shell script that passes parameters (child_process.execFile())
For this, you need to prepare a shell script first. For example, if I want to connect to a server to modify its password, I need to provide IP, user, new pwd, old pwd, and create a new shell script file change_password.sh:
The code copy is as follows:
#!/bin/sh
IP=""
NAME=""
PASSWORD=""
NEWPASSWORD=""
While getopts "H:U:P:N:" arg #The colon after the option indicates that the option requires parameters
do
case $arg in
H)
IP=$OPTARG
;;
U)
NAME=$OPTARG
;;
P)
PASSWORD=$OPTARG
;;
N)
NEWPASSWORD=$OPTARG
;;
?) #When there are options that you don't recognize, arg is?
echo "Contains unknown parameters"
exit 1
;;
esac
done
#Get userid first
USERID=`/usr/bin/ipmitool -I lanplus -H $IP -U $NAME -P $PASSWORD user list | grep root | awk '{print $1}'`
# echo $USERID
#Modify password according to userid
/usr/bin/ipmitool -I lanplus -H $IP -U $NAME -P $PASSWORD user set password $USERID $NEWPASSWORD
Then I prepare a nodejs file to call this shell script, called file_changepwd.js:
The code copy is as follows:
var callfile = require('child_process');
var ip = '1.1.1.1';
var username = 'test';
var password = 'pwd';
var newpassword = 'newpwd';
callfile.execFile('change_password.sh',['-H', ip, '-U', username, '-P', password, '-N', newpassword],null,function (err, stdout, stderr) {
callback(err, stdout, stderr);
});
It is not convenient to post the running results here, but I can use personality to ensure that it has been tested.
After reading the above, there is actually no suspense to call python scripts, which is essentially executing commands.
4. Call python script (python script itself passes parameters)
Here is a distraction. The following paragraph is a brief explanation of the parameters passed on python:
The code copy is as follows:
# -*-coding:utf-8 -*-
'''
Module required: sys
Number of parameters: len(sys.argv)
Script name: sys.argv[0]
Parameter 1: sys.argv[1]
Parameter 2: sys.argv[2]
'''
import sys
print u"Script name:", sys.argv[0]
for i in range(1, len(sys.argv)):#The parameter starts from 1
print u"parameter", i, sys.argv[i]
Running results:
I'll also prepare a nodejs file to call this python script (I made changes to py_test.py, see below), file_python.js:
The code copy is as follows:
var exec = require('child_process').exec;
var arg1 = 'hello'
var arg2 = 'jzhou'
exec('python py_test.py '+ arg1+' '+arg2+' ',function(error,stdout,stderr){
if(stdout.length >1){
console.log('you offer args:',stdout);
} else {
console.log('you don/'t offer args');
}
if(error) {
console.info('stderr : '+stderr);
}
});
The content of py_test.py is as follows:
# -*-coding:utf-8 -*-
import sys
print sys.argv
The operation results are as follows:
It's quite good, and I completed an exquisite blog for 2014. Haha~~