javascript - 在 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
,但函数res
的fixUrl
返回正确的结果,http://google.com
。
我知道这很像这里的许多问题,但经过广泛的研究和多次尝试和重写,我相信这可能是修复代码的唯一方法。
任何帮助将不胜感激。
解决方案
您可以使用为 URL 解析和解析提供实用程序的 url 模块。
const url = require('url');
const myURL = new URL('https://google.com');
console.log(myURL.host); // google.com
推荐阅读
- android - 如何在颤动中添加启动画面
- php - 将 wp_query 参数转换为 Visual Composer Post Grid 的查询字符串
- maven - Querydsl-sql 用 schema 指定表名
- javascript - 如何在新页面中打印html表格下一个缺失的列?
- django - 如何组织 Django API
- function - 如何在 sympy 中定义自定义函数?
- api - 币安价格历史精确到秒
- python - 您可以将标准偏差添加到 seaborn regplot 中的点吗?
- python - 如何查看两个 python conda 环境之间的所有差异?
- swiftui - isMomentary 上 SegmentedPickerStyle Swiftui