【问题标题】:How to make synchronous DNS requests in a nodejs script?如何在 nodejs 脚本中发出同步 DNS 请求?
【发布时间】:2019-08-04 11:37:33
【问题描述】:

我需要在我的 NodeJS 程序中使用特定的 DNS 服务器发出同步 DNS 请求(我需要实际请求,无需查找)。如果可能的话,我想使用标准的 DNS 库。我的代码在交互模式下工作,但不是在实际脚本中。我对同步问题不太满意,所以我不完全理解 await 和东西的实际作用。

这是我的代码,目前在我的脚本中:

var readline = require('readline-sync');

async function sendm(req, srv) {
    console.log("Will ask " + srv.getServers()[0] + " for " + req);
    const addresses = await srv.resolve4(req);
    console.log(addresses);
}

当用户输入以“s”开头的内容时执行该函数:

const { Resolver } = require('dns').promises;
const dns = new Resolver();
dns.setServers(["8.8.8.8"]);
// ...

var input = "";
while(input != "q") {
        input = readline.question("Command: ");
        if(/^s/g.test(input)) { // input starts with s
                console.log("Input starts with s");
                sendm("stackoverflow.com", dns);
        }
        else if(/^r/g.test(input))
                console.log("input starts with r");
        // ...
}

这是一个输出:

# nodejs debug.js
Command: s
Input starts with s
Will ask 8.8.8.8 for stackoverflow.com
Command: s
Input starts with s
Will ask 8.8.8.8 for stackoverflow.com
Command: s
Input starts with s
Will ask 8.8.8.8 for stackoverflow.com
Command: r
input starts with r
Command: r
input starts with r
Command: s
Input starts with s
Will ask 8.8.8.8 for stackoverflow.com
Command: q
[ '151.101.1.69', '151.101.65.69', '151.101.129.69', '151.101.193.69' ]
[ '151.101.1.69', '151.101.65.69', '151.101.129.69', '151.101.193.69' ]
[ '151.101.1.69', '151.101.65.69', '151.101.129.69', '151.101.193.69' ]
[ '151.101.1.69', '151.101.65.69', '151.101.129.69', '151.101.193.69' ]

我需要在程序仍在运行时处理 DNS 地址。我该怎么办?我尝试了在 DNS 库文档中找到的不同方法,但没有任何效果。你能帮帮我吗?

非常感谢!

【问题讨论】:

    标签: node.js dns


    【解决方案1】:

    作为一个异步函数,sendm 返回一个 Promise,但是 while 循环只是重新开始,因为它不知道 Promise,您可以发送一个新请求,而另一个请求在它的 await 调用上暂停。
    虽然 top level await 尚未随 node 一起提供,但您可以将整个内容包装在异步 IIFE 中,该 IIFE 将正确等待您的 dns 调用。

    (async () => {
            var input = "";
            while(input != "q") {
                    // ...
                            await sendm("stackoverflow.com", dns);
                    // ...
            }
    })();
    

    【讨论】:

      【解决方案2】:

      基本上你需要让你的while循环等待你的函数sendm的返回我认为你可以把async放在while循环之前,然后把await放在你的函数之前,尽管不是将结果存储在@ 987654324@ 它应该由函数(sendm)返回,这样它将返回一个已解决的承诺,然后才继续。如果您不能将 while 包装在异步中,只需将其粘贴在一个函数中,然后将 await 放在函数调用之前sendm。 需要明确的是,async 表示该函数是异步执行的,await 表示它返回一个已解决的承诺,并且在达到该解决状态之前不会继续执行。所以这有点像在异步函数中阻塞同步代码。

      【讨论】:

        猜你喜欢
        • 2012-06-02
        • 1970-01-01
        • 2018-01-31
        • 2018-11-13
        • 2020-10-27
        • 1970-01-01
        • 2018-12-31
        • 1970-01-01
        • 2020-09-29
        相关资源
        最近更新 更多