Be the first user to complete this post

  • 0
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:

  1. Creating a simple event emitter using nodejs
  2. Resolved - sudo npm command not found
  3. Understanding routers in express 4.0 - Visually
  4. Understanding semver versioning for your nodejs packages
  5. Disable eslint no-unused-vars warning on global functions
  6. Access the request body of a post request in your nodejs - expressjs app.
  7. Error handling in promises interview question
  8. Use es6 and es6+ in eslint with babel