【JavaScript 學習--05】Nodejs之如何呼叫 cmd 命令
阿新 • • 發佈:2019-02-20
/*For getting data from PR system API*/
var express = require('express');
var router = express.Router();
var exec = require('child_process').exec; //key require for cmd operation.
router.get("/prInfo_get", function(req, res, next) {
var url = 'https://prefix_link/';
console.log(req.query);
/* req.query will display as object when get info from blow link.
* http://127.0.0.1:3000/api/issues/prInfo_get?bl=lte-n&product=tdd-macro&branch=trunk&prNum=PR178847
* GET /api/issues/prInfo_get?bl=lte-n&product=tdd-macro&branch=trunk$prNum=PR178847
* { bl: 'lte-n',
* product: 'tdd-macro',
* branch: 'trunk',
* prNum : 'PR4478847' }
*/
var prNum = req.query.prNum;
var USER = "username";
var PASSWD = "password";
var cmdStr = "curl -u \"" + USER + ":" + PASSWD + "\" " + url + prNum;
//cmdStr = 'curl -u "username:password" https://prefix_link/PR4478847'
exec(cmdStr, function(err,stdout,stderr){
if (err) {
console.log('get weather api error:'+stderr);
} else {
var data = JSON.parse(stdout);
console.log(data);
res.send({data:data}); //send data to request link.
}
});
});
下面是單獨使用nodejs 執行 curl的例子。沒有使用者名稱和密碼。
var exec = require('child_process').exec;
var cmdStr = 'curl http://link/101010100.html';
exec(cmdStr, function(err,stdout,stderr){
if(err) {
console.log('get weather api error:'+stderr);
} else {
/*
the content of stdout is liking bellows:
{"weatherinfo":{"city":"Hongkong","cityid":"101","temp":"3","WSE":"3","qy":"1019"}}
*/
var data = JSON.parse(stdout);
console.log(data);
}
});