Runs a given script only if it is the main one called with node.
This module/package aims to help organizing main node scripts and to help with testing them as well.
npm install @everymundo/runnerLet's say you have a node.js file with a small simple http server
// server.jsconsthttp=require('http');constlogr=require('@everymundo/simple-logr');constAPP_PORT=Math.abs(process.env.APP_PORT)||8008;constrequestHandler=(req,res)=>{logr.debug(req.url);res.end('Hello Node.js Server!');};constserver=http.createServer(requestHandler);server.listen(APP_PORT,(err)=>{if(err){logr.error('something bad happened',err);throwerr;}logr.info(`server runnin on port ${APP_PORT}`);});It is a regular working code, and you can put it to work by just running:
node server.jsBut it is not really easy to test it. As soon as this file is loaded by your test 'test/server.test';
require('../server.test');That will automatically put the server to run, and that is not an ideal effect when you only want to test it.
By slightly changing the code ...
// server.jsconst{ run }=require('@everymundo/runner');consthttp=require('http');constlogr=require('@everymundo/simple-logr');constAPP_PORT=Math.abs(process.env.APP_PORT)||8008;constrequestHandler=(req,res)=>{logr.debug(req.url);res.end('Hello Node.js Server!');};constserver=http.createServer(requestHandler);constinitialize=()=>server.listen(APP_PORT,(err)=>{if(err){logr.error('something bad happened',err);throwerr;}logr.info(`server runnin on port ${APP_PORT}`);});run(__filename,initialize);... we can guarantee that it will only run its functionality when used by running node server.js but not when loading the file via require('server.js');