Search code examples
node.jsnpmnvmn

Automatically use the right version of Node for a package


I know it is possible to switch between different versions of Node using NVM, n, or similar.

Is there a convenient way for the right version of Node to automatically be used when running commands within a given package? ("Right version" being determined by the engine tag or similar).

For instance, I would like to be able to do this:

cd mypackage-that-needs-node10
npm run serve
# ... node 10 is used
cd ..
cd mypackage-that-needs-node14
npm run serve
# ... node 14 is used

Solution

  • n supports an engine label to find Node.js version from package.json, and auto which includes more sources such as a .node-version file.

    For example:

    $ n install engine
    # or run the target version of node
    $ n run auto index.js
    # or execute a command with that Node.js in path
    $ n exec auto npm run serve