Post/Code

HomeAboutUsesNow

Express, Express, Express.

  • Add static resources to Node.js server

        app.use('/static', express.static('public'));
    
  • Modularize your routes, for example, in /routes/index.js:

        const express = require("express");
        const router = express.Router();
    
        router.get('/', (req, res) => {
            ...
        });
        ...
        module.export = router;
    

    Then in your main app.js

        const routes = require('./routes');
        app.use(routes);
    
  • Setup CORS for your API app | npm i cors --save

        ...
        var cors = require("cors");
        ...
        app.use(cors({
            origin: ["http://localhost:8000"],
            methods: ["GET", "POST"],
            allowedHeaders: ["Content-Type", "Authorization"]
        }));
        ...
    
  • Logging with Morgan | npm i morgan --save

    ...
    var morgan = require('morgan');
    ...
    app.use(morgan('common'));
    
  • Configuring Node.js clusters in cluster.js | Clusters

        var cluster = require("cluster");
        var os = require("os");
        
        const CPUS = os.cpus();
        
        if (cluster.isMaster) {
            for (var i = 0; i < CPUS.length; i++) { 
                cluster.fork() 
            });
            
            cluster.on("listening", function(worker) {
                console.log(`Cluster ${ worker.process.pid } connected`);
            });
        
            cluster.on("disconnect", function(worker) {
                console.log(`Cluster ${ worker.process.pid } disconnected`);
            });
    
            cluster.on("exit", function(worker) {
                console.log(`Cluster ${ worker.process.pid } is dead`);
                // Ensuring a new cluster will start if an old one dies
                cluster.fork();
            });
        } else {
            require("./index.js");
        }
    

    Then run: nodemon cluster.js

  • GZIP Compression | npm i compression --save | Compression

        ...
        var compression = require('compression');
        ...
        app.use(compression(6)); // number indicates level of compression
    

  • Protect from some forms of attach with Helmet | npm i helmet --save

        ...
        var helmet = require('helmet');
        ...
        app.use(helmet());
    

Credit: JScrambler Blog