NodeJs global.process

Viewed 214

Why is the Object.keys function on the global object not returning the 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',
1 Answers

process is not actually a key on the global object as of node version 12 (Described in the changelog https://nodejs.org/tr/blog/uncategorized/10-lts-to-12-lts/#notable-changes-in-node-js-12-0-0, implemented through PR https://github.com/nodejs/node/pull/26882). Instead it has a defined getter for it. E.g. try out global.__lookupGetter__('process') and you should see that you get a function back.

> 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',
...

The reason for the change as described in the 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.

...

The other referenced PR is https://github.com/nodejs/node/pull/26334 which is described as:

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.

Related