devtools.js 858 Bytes
'use strict';

const os = require('os');
const fs = require('fs');
let devHost;

const getFirstLocalIp = () => {
    const ifaces = os.networkInterfaces();
    const res = [];

    Object.keys(ifaces).forEach(function(ifname) {
        ifaces[ifname].forEach(function(iface) {
            if ('IPv4' !== iface.family || iface.internal !== false) {
                return;
            }

            res.push(iface.address);
        });
    });

    return res[0] || 'localhost';
};

if (!devHost) {
    fs.readFile('.devhost', (err, buf) => {
        if (!err) {
            devHost = JSON.parse(buf.toString()).host;
        } else {
            devHost = getFirstLocalIp();
        }
    });
}

module.exports = () => {
    return (req, res, next) => {
        Object.assign(res.locals, {
            devHost: devHost
        });

        next();
    };
};