DEV Community

Jochem Stoel
Jochem Stoel

Posted on

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. =)

Top comments (1)

Collapse
 
jochemstoel profile image
Jochem Stoel

A couple of days ago I posted this snippet for easy access to Node's core modules but it wasn't easy enough because nobody wants to copy paste a snippet every time. That is arguably even more annoying than typing var fs = require('fs') every time.

I ended up publishing this module that wraps it to an elegant functional reactive oneliner. =p Just npm i internal.modules.

/* like this */
const { fs, childProcess, http } = require('internal.modules')
fs.writeFileSync('directories.txt', childProcess.execSync('dir'))

/* or even this */
const { mkdir, unlink } = require('internal.modules').fs 
unlink('directories.txt', error => error ? console.error(error) : console.log('file was deleted.'))