JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 1999
  • Score
    100M100P100Q106310F
  • License MIT

self property in Node.js

Package Exports

  • node-self
  • node-self/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (node-self) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

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 light weight
  • Pure Javascript
  • Zero dependency
  • Safe
  • No Bundler/Transpiler/Other things
  • No more bugs

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 : null
}()

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'

Changelog

  • 2022.09.29 (v1.0.1)
    • Change to loose equality comparison because, typeof operator is always return string value.
    • Now following Semantic Versioning
  • 2021.11.02 (v1.0.0-d)
  • 2020.05.16: Update code (v1.0.0-c)
  • 2020.05.14: Fix condition, Update document (v1.0.0-b)
  • 2020.05.13: Fix condition (v1.0.0-a)
  • 2020.05.13: First Release (v1.0.0)

License

MIT