Node.js:node.js中是否存在`http.get`方法的同步版本?

时间:2012-03-03 04:23:04

标签: http node.js asynchronous get synchronous

node.js中是否存在http.get方法的同步版本?

类似的东西:

http.getSync({
    host: 'google.com', 
    port: 80, 
    path: '/'
}, function(response){  

});

console.log(response)

有时会非常有用。

2 个答案:

答案 0 :(得分:3)

有一个非常容易使用的sync-request库。在内部,它同步生成子进程并使用then-request,因此选项与该库类似。

正如其他人所说,我会提醒您不要在运行时逻辑中使用它。但是,它可以非常方便地加载配置。

如果您正在加载配置,则另一个策略可以使用单独的脚本来启动您的流程。例如:

var http = require("http"),
    cp   = require("child_process");

// Starting process
if (process.argv.length < 3) {
    return http.get("http://www.google.com/index.html", function(res) {
        var config = {
            statusCode : res.statusCode,
            headers    : res.headers
        };

        cp.fork(module.filename, [JSON.stringify(config)]);
    });
}

// Config provided
var config = JSON.parse(process.argv[2]);

console.log(config.statusCode);

答案 1 :(得分:-9)

不,没有。老实说,我没有看到用例。

如果您扩展用例或您尝试解决的问题,我会尝试回答这个问题。