Managing multiple versions of Node.js with nix?

Alright! I finally learned how to install it from the tarball release. This is what I have:

default.nix:

let
  pkgs = import <nixpkgs> {};
  installNodeJS = import ./nodejs.nix;

in installNodeJS {
  inherit pkgs;
  version = "13.6.0";
  sha256 = "00f01315a867da16d1638f7a02966c608e344ac6c5b7d04d1fdae3138fa9d798";
}

nodejs.nix:

{ pkgs ? import <nixpkgs> {}, version, sha256 }:

  let
    inherit (pkgs) stdenv autoPatchelfHook platforms fetchurl;
    inherit (stdenv) mkDerivation lib;
  
  in mkDerivation {
    inherit version;
  
    name = "nodejs-${version}";
  
    src = fetchurl {
      url = "https://nodejs.org/dist/v${version}/node-v${version}-linux-x64.tar.xz";
      inherit sha256;
    };

    # QUESTION: put glib and autoPatchelfHook in nativeBuildInputs or buildInputs?
    nativeBuildInputs = with pkgs; [autoPatchelfHook];
    buildInputs = with pkgs; [glib];

    installPhase = ''
      echo "joe is installing nodejs"
      mkdir -p $out
      cp -R ./ $out/
    '';
  
    meta = {
      description = "Event-driven I/O framework for the V8 JavaScript engine";
      homepage = https://nodejs.org;
      license = lib.licenses.mit;
      platforms = lib.platforms.linux;
    };

    #TODO do I need this?
    #passthru.python = python2; # to ensure nodeEnv uses the same version
  }

Then in that folder I can run nix-build to build it, then ./result/bin/node to run it.

@shanesveller @savannidgerinel I’m not sure how to make a new shell with the new node in my PATH. How might I do that with nix?

For now I just set export PATH=/path/to/result/bin/:$PATH locally in my current shell, which is easy enough to get working with differing versions.

1 Like