Simple snippet to make Node's built in modules globally accessible

jochemstoel

Jochem Stoel

Posted on September 16, 2018

Simple snippet to make Node's built in modules globally accessible

I am very lazy and don't want to type the same fs = require('fs') in every little thing I'm doing and every temporary file that is just a means to an end and will never be used in production.

I decided to share this little snippet that iterates Node's internal (built in) modules and globalizes only the valid ones. The invalid ones are those you can't or shouldn't require directly such as internals and 'sub modules' (containing a '/'). Simply include globals.js or copy paste from below.

The camelcase function is only there to convert child_process into childProcess. If you prefer to have no NPM dependencies then just copy paste the function from GitHub or leave it out entirely because camelcasing is only cute and not necessary.

globals.js

/* https://github.com/sindresorhus/camelcase/blob/master/index.js */
const camelCase = require('camelcase')

Object.keys(process.binding('natives')).filter(el => !/^_|^internal/.test(el) && [
    'freelist',
    'sys', 
    'worker_threads', 
    'config'
].indexOf(el) === -1 && el.indexOf('/') == -1).forEach(el => {
    global[camelCase(el)] = require(el) // global.childProcess = require('child_process')
})
Enter fullscreen mode Exit fullscreen mode

Just require that somewhere and all built in modules are global.

require('./globals')

fs.writeFileSync('dir.txt', childProcess.execSync('dir'))
Enter fullscreen mode Exit fullscreen mode

These are the modules exposed to the global scope (Node v10.10.0)

asyncHooks
assert
buffer
childProcess
console
constants
crypto
cluster
dgram
dns
domain
events
fs
http
http2
https
inspector
module
net
os
path
perfHooks
process
punycode
querystring
readline
repl
stream
stringDecoder
timers
tls
traceEvents
tty
url
util
v8
vm
zlib
Enter fullscreen mode Exit fullscreen mode

Um. I suggest we start using the #snippet tag to share snippets with each other. =)

💖 💪 🙅 🚩
jochemstoel
Jochem Stoel

Posted on September 16, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related