Library functions

Builtins

These are available by default in the Nix language, reference: Nix manual

String to File

nix-repl> builtins.toFile "hello.txt" "Hello World!"
"/nix/store/r4mvpxzh7rgrm4j831b2yi90zq64grqm-hello.txt"
$ cat /nix/store/r4mvpxzh7rgrm4j831b2yi90zq64grqm-hello.txt
Hello World!

Read File

nix-repl> builtins.readFile ./code/03-nix-basics/03-files/hello.txt
"Hello World!"

nix-repl> builtins.readFile /nix/store/r4mvpxzh7rgrm4j831b2yi90zq64grqm-hello.txt
"Hello World!"

nix-repl> builtins.readFile (builtins.toFile "hello" "Hello World!")
"Hello World!"

Fetch URL

nix-repl> example = builtins.fetchurl "https://scrive.com/robots.txt"

nix-repl> example
[0.0 MiB DL] downloading 'https://scrive.com/robots.txt'"/nix/store/r98i29hkzwyykm984fpr4ldbai2r8lhj-robots.txt"

nix-repl> example
"/nix/store/r98i29hkzwyykm984fpr4ldbai2r8lhj-robots.txt"
$ cat /nix/store/r98i29hkzwyykm984fpr4ldbai2r8lhj-robots.txt
User-agent: *
Sitemap: https://scrive.com/sitemap.xml
Disallow: /amnesia/
Disallow: /api/

URLs are only fetched once locally!

Fetch Tarball

nix-repl> nodejs-src = builtins.fetchTarball
            "https://nodejs.org/dist/v14.15.0/node-v14.15.0-linux-x64.tar.xz"
nix-repl> nodejs-src
"/nix/store/6wkj0blipzdqbsvwv03qy57n4l33scpw-source"
$ ls /nix/store/6wkj0blipzdqbsvwv03qy57n4l33scpw-source
bin  CHANGELOG.md  include  lib  LICENSE  README.md  share

Nixpkgs library functions

These have to be imported from the nixpkgs repository, reference: Nixpkgs manual

nix-repl> :l <nixpkgs>

nix-repl> object = { a = 1; b = 2; c = true; }

nix-repl> lib.attrNames object
[ "a" "b" "c" ]

nix-repl> lib.attrValues object
[ 1 2 true ]

Finding the main executable of a program:

nix-repl> lib.getExe mpv      
"/nix/store/rw37dfsb0sijl5ld7ihc17295xdr66q5-mpv-with-scripts-0.36.0/bin/mpv"