Skip to content

Instantly share code, notes, and snippets.

@nrolland
Last active January 10, 2022 15:32
Show Gist options
  • Save nrolland/a12a93b2d797a8ea1a8ff420741ecc1d to your computer and use it in GitHub Desktop.
Save nrolland/a12a93b2d797a8ea1a8ff420741ecc1d to your computer and use it in GitHub Desktop.
Practical Nix

Prerequisites

  • nix installed
  • "nix flake experimental feature" enabled

cf Practical Nix Flakes

What

Shell what
nix run nixpkgs#hello just launch now
nix shell nixpkgs#hello get a shell with it
nix profile install nixpkgs#hello symlink it cf nix profile help
nix build nixpkgs#hello build it
./result/bin/hello run a built program
$(nix build --json nixpkgs#hello | jq -r .[].outputs.out)/bin/hello build and run
nix-build -E "with import <nixpkgs> { };hello" build and run
nix-build -E "$(cat default.nix)" build and run
$(nix-build)/bin/hello build and run with default.nix below
# in default.nix
 { pkgs ? import <nixpkgs> {} }:
 pkgs.hello

Exemple

JS

I don't have node on my computer but I want to run this :

//in file  helloworld.js
const http = require('http'); // Loads the http module

http.createServer((request, response) => {

    // 1. Tell the browser everything is OK (Status code 200), and the data is in plain text
    response.writeHead(200, {
        'Content-Type': 'text/plain'
    });

    // 2. Write the announced text to the body of the page
    response.write('Hello, World!\n');

    // 3. Tell the server that all of the response headers and body have been sent
    response.end();

}).listen(1337); // 4. Tells the server what port to be on

like so

$(nix-build -E "with import <nixpkgs> { };nodejs")/bin/node helloworld.js

Haskell

I don't have haskell on my computer but I want to run this

-- in file helloworld.hs
{-# LANGUAGE OverloadedStrings #-}

import Data.ByteString.Char8 ()
import Data.Conduit
import Data.Conduit.Network

main :: IO ()
main =
  runTCPServer
    (serverSettings 8080 "127.0.0.1")
    run
  where
    response = "HTTP/1.0 200 OK\nContent-Length: 14\n\nHello, World!\n"
    run :: AppData -> IO ()
    run ad = runConduit $ appSource ad $$ yield response =$ appSink ad

like so

$(nix-build -E "with import <nixpkgs> { };haskellPackages.ghcWithPackages(p: with p; [network HTTP conduit conduit-extra])")/bin/runghc -v helloworld.hs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment