Write binary file to nix store

I want to store my wallpaper in my NixOS config and have it in the Nix store, but I can’t figure out how to load and write a binary file. I first tried using the trivial builders:

let wallpaper = pkgs.writeText "wallpaper.png" (builtins.readFile ./wallpaper.png); in ...

But writeText and readFile seem like they only work with UTF-8 strings. How can I do this?

no need to read it, the path itself is enough:

let wallpaper = ./wallpaper.png; in ...

it’ll be copied to the store automatically if it is used anywhere.

1 Like

Yea, Nix can’t read arbitrary binary files with readFile; but it’s nothing to do with utf8. It simply can’t tolerate null bytes since currently nix strings are encoded with null termination (if I remember correctly).

So yea, the correct thing to do is just use the file literal directly as @pennae suggests.

1 Like

For reproducibility reasons, you should rely on builtins.path:

  wallpaper = builtins.path {
    path = ./wallpaper.png; 
    name = "my-awesome-wallpaper"; 
  . . .

Read about this below:

1 Like

I’ll note that this isn’t a problem with anything that’s not a ./. or ./.. or similar (unless you want to change the actual file name later), or with flakes (if you’re using them)