【JavaScript 学习--05】Nodejs之如何调用 cmd 命令

下面是从网页http://127.0.0.1:3000/api/issues/prInfo_get?bl=lte-n&product=tdd-macro&branch=trunk&prNum=PR178847 发起请求,触发curl命令获取数据,并转换为JSON 返回给页面。

/*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);
    }
});

你可能感兴趣的:(javascript,nodejs,JavaScript)