使用Node.js执行Sync Get请求

时间:2013-12-16 07:47:19

标签: node.js

我试图从服务器收到的响应与url的命令行参数传递的顺序相同。但是它不执行同步操作请帮忙。 我对javascript和节点比较陌生。 请在下面找到我的代码:

var http = require('http');
var bl = require('bl');
var fs = require('fs');
var q = [];
var count = 0;
q[0] = getRequest(process.argv[2]);
q[1] = getRequest(process.argv[3]);
q[2] = getRequest(process.argv[4]);
function getRequest(url) {
    var val;
    http.get(url,function (res) {
        res.on('end', function () {
            count++;
        }),
            res.pipe(bl(function (error, data) {
                val = data.toString();
                if (error) {
                    console.log(error);
                }
                else {
                    console.log(val);
                }
            }))
    }).on('error', function (e) {
            console.log("Got error: " + e.message);
        });
    return val;
}

if (count == 3) {
    for (var i = 0; i < q.length; i++) {
        console.log[q[i]];
    }
}

3 个答案:

答案 0 :(得分:3)

var http = require('http');
var bl = require('bl');

// data should return via callback = function(err, data)
function getRequest(url, callback) {
    http.get(url, function(res) {
        res.pipe(bl(function(error, data) {
            callback(error, data);
        }))
    }).on('error', function(e) {
        callback(error);
    });
}

// npm install async
var async = require('async');

async.map(process.argv.slice(2), getRequest, function (err, data_array) {
    data_array.forEach( function (data, i) {
        console.log(i, data.toString('utf8'));

    });
})

另存为test.js并从终端运行:

npm install bl
npm install async
node test.js http://api.openkeyval.org/hello1 http://api.openkeyval.org/hello2 

输出:

0 'hello one'
1 'hello two'

async.map会像这样调用getRequest:

getRequest(url1, function (e, data) {
    console.log(data);
    getRequest(url2, function (e, data) {
        console.log(data);
        getRequest(url3, function (e, data) {
            console.log(data);
        })
    });
});

答案 1 :(得分:2)

另一种方法,不使用任何插件或附件进行异步实现:

var http = require('http')
var bl = require('bl')
var results = []
var count = 0

function printResults () {
    for (var i = 0; i < 3; i++)
        console.log(results[i])
}

function httpGet (index) {
    http.get(process.argv[2 + index], function (response) {
        response.pipe(bl(function (err, data) {
            if (err)
                return console.error(data)

            results[index] = data.toString()
            count++

            if (count == 3) // yay! we are the last one!
                printResults()
        }))
    })
}

for (var i = 0; i < 3; i++)
    httpGet(i)

或没有任何附加组件或插件

var http = require('http')
//var bl = require('bl') // if you want to use bl

var url1 = process.argv[2]
var url2 = process.argv[3]
var url3 = process.argv[4]

// data should return via callback = function(err, data)
function getRequest(url, callback) {

    http.get(url, function(response) {

        response.setEncoding('utf8')

        response.on('error', function(e) {
            callback(error);
        })

        var allData = ''
        response.on('data', function(data) {
            allData += data
        })

        response.on('end', function() {
            callback(null, allData)
        })

        // Would be the result using bl
        /*
        response.pipe(bl(function(err, data) {
            callback(err, data.toString())
        }))
        */

    })

}

// This can be placed in a for loop
getRequest(url1, function (e, data) {
    console.log(data)
    getRequest(url2, function (e, data) {
        console.log(data)
        getRequest(url3, function (e, data) {
            console.log(data)
        })
    })
})

所以你第一次尝试就没那么远了!

答案 2 :(得分:1)

由于它是异步返回将没有用。但是当你得到结果时,你可以推它。

        res.pipe(bl(function (error, data) {
            val = data.toString();
            q.push(val);
            if (error) {
            ...

或者如果你想使用计数,你可以这样做:

        res.pipe(bl(function (error, data) {
            val = data.toString();
            q[count] = val;
            if (error) {
            ...

然后你可以简单地打电话:

getRequest(process.argv[2]);
getRequest(process.argv[3]);
getRequest(process.argv[4]);