---
title: "Primordials in Node.js"
description: "What are Primordials in Node.js and why do they exist? Practical notes and code examples on Primordials in Node.js by in JS."
url: "https://h3manth.com/scribe/primordials-in-node/"
canonical_url: "https://h3manth.com/scribe/primordials-in-node/"
markdown_url: "https://h3manth.com/scribe/blog/primordials-in-node.md"
publishDate: "2021-09-09T00:00:00.000Z"
author: "Hemanth HM"
category: "node"
tags: ["node","javascript","internals"]
word_count: 580
reading_time_minutes: 3
x_markdown_tokens: 1255
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# Primordials in Node.js

> What are Primordials in Node.js and why do they exist? Practical notes and code examples on Primordials in Node.js by in JS.

If you are a curious programmer who likes reading source code and if you happen to have ever read Node.js's source you would have noticed this term called `primordial` and would have seen its usage like:

```javascript
const {
  ObjectCreate,
  ObjectDefineProperty,
  RegExp,
  RegExpPrototypeExec,
  SafeArrayIterator,
  StringPrototypeToLowerCase,
  StringPrototypeToUpperCase,
} = primordials;
```

You get into your REPL and hit `primordials` and notice that `Uncaught ReferenceError: primordials is not defined`

So, what are these [primordials](https://github.com/nodejs/node/blob/master/lib/internal/per_context/primordials.js)?

From the comments in source:

> This file subclasses and stores the JS builtins that come from the VM so that Node.js's builtin modules do not need to later look these up from the global proxy, which can be mutated by users.

Interesting, so this is here to avoid any problems that might occur in case user overwrites anything in `prototype` chain or the global proxy.

## Example

Say somewhere in the node internal logger lib we have:

```javascript
Object.defineProperty(logger, 'enabled', {
  get() {
    return test();
  },
  configurable: true,
  enumerable: true
});
```

If a user defined lib overrides or deletes `Object.defineProperty` the internal logger's `defineProperty` will fail to execute or behave as per expectations, hence we would need primordials thereby we could rewrite the same code as:

```javascript
const {
  ObjectDefineProperty,
} = primordials;

ObjectDefineProperty(logger, 'enabled', {
  get() {
    return test();
  },
  configurable: true,
  enumerable: true
});
```

## Performance Concern

> Use of primordials have sometimes a dramatic impact on performance, please benchmark all changes made in performance-sensitive areas of the codebase.
> See: https://github.com/nodejs/node/pull/38248

## Digging into the Code

First up we notice aliases for Reflect functions:

```javascript
const {
  defineProperty: ReflectDefineProperty,
  getOwnPropertyDescriptor: ReflectGetOwnPropertyDescriptor,
  ownKeys: ReflectOwnKeys,
} = Reflect;
```

Then we have two interesting methods `uncurryThis` and `applyBind` which are basically:

```javascript
func => Function.prototype.call.bind(func)
func => Function.prototype.apply.bind(func)
```

It is using `bind.bind(apply)` or `bind.bind(call)` to avoid using `Function.prototype.bind` and `Function.prototype.apply` or `Function.prototype.call` after users may have mutated it.

But `delete Function.prototype.call` will still break most of node, also `delete Array.prototype[Symbol.iterator]` will break everything most anywhere there's `for-of`, or `spreading` an array. [Thanks to @ljharb for this info]

Methods that accept a variable number of arguments, and thus it's useful to also create `${prefix}${key}Apply`, which uses `Function.prototype.apply`, instead of `Function.prototype.call`, and thus doesn't require iterator destructuring.

## Interesting Cases

- It creates copies of configurable value properties, URI handling functions, namespace objects and intrinsic objects.
- Intrinsic objects that require a valid `this` to call static methods are treated as a special case.
- Abstract intrinsic objects that are not directly exposed on the global object is another case.
- Creates safe iterators, Map, WeakMap, Set, WeakSet, FinalizationRegistry and Promises.

## createSafeIterator

```javascript
const createSafeIterator = (factory, next) => {
  class SafeIterator {
    constructor(iterable) {
      this._iterator = factory(iterable);
    }
    next() {
      return next(this._iterator);
    }
    [SymbolIterator]() {
      return this;
    }
  }
  ObjectSetPrototypeOf(SafeIterator.prototype, null);
  ObjectFreeze(SafeIterator.prototype);
  ObjectFreeze(SafeIterator);
  return SafeIterator;
};
```

## Frozen Intrinsics Flag

It is worth noting about `frozen-intrinsics` flag which enables experimental frozen intrinsics like `Array` and `Object`. Support is currently only provided for the root context and no guarantees are currently provided that `global.Array` is indeed the default intrinsic reference.

If you were to start your REPL with `--frozen-intrinsics` flag:

```javascript
> Object.defineProperty
// [Function: defineProperty] Function <Function <[Object: null prototype] {}>>

> delete Object.defineProperty
// false

> Object.defineProperty = null
// null

> Object.defineProperty
// [Function: defineProperty] Function <Function <[Object: null prototype] {}>>
```

Hope you had fun scratching the surface on Primordials!

P.S: Thanks to [Guy Bedford](https://twitter.com/guybedford) for reviewing this post.
