gpt4 book ai didi

javascript - 在单个模块中覆盖 node.js querystring.escape

转载 作者:数据小太阳 更新时间:2023-10-29 04:42:37 25 4
gpt4 key购买 nike

我想在对象上使用 querystring.stringify。对字符串的要求有点不合标准,星号、斜杠和撇号都需要转义。 Querystring 不会转义这些(它们通常不需要)但是文档说 querystring.escape 是专门公开的,以便我们可以用我们自己的函数覆盖它。以下内容对我有用:

querystring.escape = function(str) {
str = encodeURIComponent(str)
.replace(/\*/g, '%2A')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')
.replace(/'/g, '%27');
return str;
};

我唯一担心的是,如果我理解正确,这可能会改变其他模块的行为,这些模块将来可能也需要查询字符串(具有正常的转义函数)。 node.js 文档说模块只加载一次,原始实例返回给后续的 require 调用。有没有办法强制这个特定的查询字符串实例是唯一的?

显然,我可以编写一个包装器,在常规调用 querystring.stringify 之后进行替换,但我很好奇,因为标准 Node 模块真的有一个“全局”设置对我来说似乎很奇怪,除非有毕竟,实际上是某种需要唯一实例的方法。

最佳答案

Is there a way for me to force this particular instance of querystring to be unique?

不是真的。 Node 的 module caching是每个进程并且 based on the module's filepath .

更改不会跨入/跨出 Child ProcessesClusters .因此,您可以通过其中之一将脚本与其自己的 querystring 隔离。

但是,在同一个进程中,Node 没有提供官方方法来绕过它来为单个模块检索唯一实例。


this might change the behavior of other modules that might also require querystring (with its normal escape function) in the future.

好吧,如果 URL 编码的值有额外的编码字符,它仍然有效。只是通常他们不需要。

而且,我想,有可能影响将期望放在编码值上的模块。但是,这通常是一个奇怪的选择(异常(exception)情况是对您自己的 querystring.escape 进行单元测试)。所以,只要能正常解码,应该没问题。

querystring.escape = function (str) { /* ... */ }; // your function here

var sample = "a(b*c)'d";

var encoded = querystring.escape(sample);
console.log(encoded); // a%28b%2ac%29'd

var decoded = querystring.unescape(encoded);
console.log(decoded); // a(b*c)'d
console.log(decoded === sample); // true

并且,能够覆盖 querystring.escapequerystring.unescape是设计使然:

The escape function used by querystring.stringify, provided so that it could be overridden if necessary.

关于javascript - 在单个模块中覆盖 node.js querystring.escape,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17983532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com