nodejs调用linux命令

(1).调用curl命令:
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 {
/*
这个stdout的内容就是上面我curl出来的这个东西:
{"weatherinfo":{"city":"北京","cityid":"101010100","temp":"3","WD":"西北风","WS":"3级","SD":"23%","WSE":"3","time":"21:20","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB","njd":"暂无实况","qy":"1019"}}
*/
var data = JSON.parse(stdout);
console.log(data);
}
});
(2).调用ls -l命令
var exec = require('child_process').exec;
var cmdStr = 'ls -l';
exec(cmdStr, function (err, stdout, srderr) {
if(err) {
console.log(srderr);
} else {
console.log(stdout);
}
});
(3).调用一个shell脚本(注意:根据代码,test.sh脚本文件需要保存在与nodejs同目录下)
var exec = require('child_process').execFile;
exec('./test.sh',{encoding:'utf8'},function (err,stdout,stderr){
if (err){
console.log(err);
return;
}
console.log(stdout)
});

你可能感兴趣的:(nodejs)