Saturday, February 29, 2020

Install local packages with npm link and npm config set prefix

In nodejs if you have a Bin package that depends on a Lib package, and before publishing a new version of Lib you want to test that local changes to Lib do not break Bin, then you can do something like this to link your local copy of Bin to your local copy of Lib:

cd Bin/ && npm link ../Lib/

A problem with this (at least on Ubuntu linux) is that npm link creates a soft link to Lib/ in npm's global folder (/usr/lib/node_modules/ on Ubuntu). So npm link both requires sudo and has a broader affect on the local system than what you want. A solution to this problem is to change npm's global prefix for your login to $HOME/.local, and add $HOME/.local/bin/ to your PATH:

npm config set prefix "$HOME/.local" --global

Now npm install --global bla installs bla under $HOME/.local/lib/node_modules/, and npm link ... sets up links there too, and testing Bin with Lib is a little less painful.

Thursday, February 06, 2020

simple expressjs logging middleware

There is a small trick to configure an expressjs middleware function to capture a request's run time and status. Here it is:

const serverLogger = (req, res, next) => {
    const startMs = Date.now();
    res.on("finish", () => {
        log.info(
            {
                req: {
                    path: req.path,
                },
                res: {
                    statusCode: res.statusCode,
                },
                timeMs: (Date.now() - startMs),
            },
        );
    });
    next();
};

app.use(serverLogger);