node-self
TypeScript icon, indicating that this package has built-in type declarations

1.0.2 • Public • Published

node-self

🤙 self property in Node.js

npm version npm downloads

Table of contents

What is this?

You can use self property in Node.js via this module.

// In Browser (Window context)
console.log(self); // Window { ... }

// In Browser (Dedicate worker context)
console.log(self); // DedicatedWorkerGlobalScope { ... }

// But, in Node.js
console.log(self); // ReferenceError: self is not defined

Why?: self property is not implemented in Node.js.

Features

You can use self property in Node.js.

  • Super lightweight
  • Pure Javascript
  • Zero dependencies

Compatibility

Both Browser and Node.js.

How to use?

Just use self. It's returns appropriate Global Object (Context Dependent)

Import index.js

// CommonJS
require('node-self');

// ES6+
import 'node-self';

or paste this code on the top

void !function () {
  typeof self == 'undefined'
    && typeof global == 'object'
    && (global.self = global);
}();

There are can be self (Global Object)

  • Browser
    • Window
    • WorkerGlobalScope
      • DedicatedWorkerGlobalScope
      • SharedWorkerGlobalScope
      • ServiceWorkerGlobalScope
  • Node.js
    • global
self;

// Browser
self === window; // true

// Node.js
self === global; // true

How it works?

This project using typeof operator trickly.

typeof operator always return a string. Even with undeclared identifiers, it will return 'undefined' instead of throwing an error.

undeclared; // ReferenceError: undeclared is not defined

typeof undeclared; // 'undefined'

  • typeof self == 'undefined': Check existing self identifier (should be undefined)
  • typeof global == 'object': Check current context is Node.js
  • global.self = global: Define self and assign reference of global object

License

MIT

Readme

Keywords

none

Package Sidebar

Install

npm i node-self

Weekly Downloads

1,963

Version

1.0.2

License

MIT

Unpacked Size

5 kB

Total Files

9

Last publish

Collaborators

  • ghlee