首页 > 解决方案 > 在 Node.js 函数中使用 `replace`

问题描述

我正在尝试编写一些代码,该代码将采用包含部分 URL 的字符串google.com,并将它们转换为完整的 URL,例如https://google.com.

我对 Node.js 非常缺乏经验,我仍在努力理解异步性的概念。

我正在尝试使用回调而不是诸如 promises 和 async/await 之类的东西,并且在我的脑海中,以下代码应该可以工作:

exports.rectifyDocumentURLs = function(baseUrl, document, callback) {
    callback(null,
        document.replace(url_patterns.any, (match) => {
            return exports.fixUrl(match, baseUrl, (err, res) => {
                if (err) {
                    callback(err, null)
                }

                return res
            })
        })
    )
}

url_patterns.any是一些匹配任何类型代码的正则表达式代码,该函数exports.fixUrl是一个函数,它将获取部分 URL 并以其完整形式返回它。

当我像这样运行代码时

exports.rectifyDocumentURLs("https://google.com", "google.com", (rectifyErr, rectifyRes) => {
    console.log(rectifyRes)
})

当前代码只是返回undefined,但函数resfixUrl返回正确的结果,http://google.com

我知道这很像这里的许多问题,但经过广泛的研究和多次尝试和重写,我相信这可能是修复代码的唯一方法。

任何帮助将不胜感激。

标签: javascriptasynchronous

解决方案


您可以使用为 URL 解析和解析提供实用程序的 url 模块。

const url = require('url');
const myURL = new URL('https://google.com');
console.log(myURL.host); // google.com

推荐阅读