Node CommonJS Example Library Template

If you want to make a new CommonJS module for Node, you can use the following as a template file (we’ll call this ‘detector.js’, but obviously you can name it whatever you want):

"use strict";
 
let _ = require('lodash');
 
exports.functionA =
  (data) => {
    return data;
  };
 
exports.functionB =
  (data) => {
    return data;
  };

Then, when you want to use it, you can pull it in with require (note this is in the same folder as the module I’ve named detector):

"use strict";
 
let express = require('express'),
    _ = require('lodash'),
    Sequelize = require('sequelize'),
    passport = require('passport'),
    http = require('http'),
    db = require('./models'),
    detector = require('./detector');
 
app.get('/preview/:alert_id', (req, res) => {
  let id = req.params.alert_id;
 
  db.Alert.find(
    {where: {
      id: id,
      UserId: req.user.id
      }})
  .then(
    (alert) => detector.functionA(alert)
  )
  .then(
    (alert) => detector.functionB(alert)
  )
});

This example shows how you can use the functions defined in the detector module as well (this is in an ExpressJS app on heroku)

Interested in JavaScript? I send out weekly, personalized emails with articles and conference talks. Click here to see an example and subscribe.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *