Be the first user to complete this post
|
Add to List |
Dynamic module loading with require
Let's say we have
./darwin.js
for mac, ./win32.js
for Windows in the current working directory. And we want to require one of them in ./index.js
based on which platform the file is being ran. This is one of technique with require, that we can do computation inside it. Novice way of doing is the following:
if (os.platform() === "mac")
var platform = require('./darwin.js');
else if (os.platform() === "win32")
var platform = require('./win32.js');
Instead of above if...else conditional statments, we can write the following:
var platform = require("./" + os.platform());
Also Read:
- nodejs: generate uuid / guid
- Use node in es6 syntax with babel transpiling
- Understanding nodejs module exports and require
- Send email using nodejs and express in 5 simple steps