gpt4 book ai didi

node.js - NodeJs global.process

转载 作者:行者123 更新时间:2023-12-03 12:14:55 25 4
gpt4 key购买 nike

为什么是Object.keys全局对象上的函数不返回 process field ?

> Object.keys(global)
[
'global',
'clearInterval',
'clearTimeout',
'setInterval',
'setTimeout',
'queueMicrotask',
'clearImmediate',
'setImmediate'
]
> global.process
process {
version: 'v13.7.0',
versions: {
node: '13.7.0',
v8: '7.9.317.25-node.28',
uv: '1.34.1',

最佳答案

process从 Node 版本 12 开始,实际上不是全局对象上的键(在更改日志中描述 https://nodejs.org/tr/blog/uncategorized/10-lts-to-12-lts/#notable-changes-in-node-js-12-0-0 ,通过 PR https://github.com/nodejs/node/pull/26882 实现)。相反,它有一个定义的 setter/getter 。例如。试用 global.__lookupGetter__('process')你应该看到你得到了一个函数。

> Object.keys(global)
[
'global',
'clearInterval',
'clearTimeout',
'setInterval',
'setTimeout',
'queueMicrotask',
'clearImmediate',
'setImmediate'
]
> global.__lookupGetter__('process')
[Function: get]
> global.__lookupGetter__('process')()
process {
version: 'v13.7.0',
versions: {
node: '13.7.0',
...
PR中描述的更改原因:

This implements just the semver major breaking changes from #26334 Restrict process and Buffer globals to CommonJS, which is to make global.process and global.Buffer getters / setters over value properties.

...


另一个引用的 PR 是 https://github.com/nodejs/node/pull/26334它被描述为:

This PR deprecates access to global.process and global.Buffer access in ECMAScript modules only, while ensuring they continue to behave fine for all CommonJS modules and contexts providing comprehensive backwards compatibility.

This is done by making them getters which check the context in which they are called and throw when inside an ECMAScript module. To avoid this getter slowpath in accesses, process and Buffer are also added as a context to the compileFunction wrapper in CJS. In addition these getters are only defined as soon as there is a load of an ECMAScript module to avoid any slowdowns in these cases.

The benefits of this are that then ECMAScript modules don't by default have to assume access to all the root-level-security functions and properties on process allowing access control to be added in future, as well as helping towards browser compatibility by making process an import.

ECMAScript modules share the same realm global, so there isn't a way to do this otherwise. In addition once users start running and writing and publishing ECMAScript modules in Node.js that assume the process and Buffer globals exist, it becomes very difficult to change this then.

For these reasons I think it is quite important to land this with the ECMAScript modules implementation in Node.js to provide these properties, or risk never being able to provide them at all in Node.js due to ecosystem compatibility constraints.

关于node.js - NodeJs global.process,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61034052/

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