Writing and Reading Files Using NodeJS in NextJS App Router

janac
3 min readFeb 10, 2024

JavaScript is used on the frontend and backend.

Does the guy’s right hand only have 4 fingers? Source — Bing Image Creator

Frontend: Read files, no writing.

On the frontend, we can read files when the user uploads them, but we can’t write files programmatically — a user would have to initiate a download to write files from a website to their computer. This makes sense from a security stand point — imagine if a website could just start writing files on to your computer as soon as you visited it, without clicking on anything. Viruses and keyloggers would be every where.

This confused me at first since there are File APIs in JavaScript that are accessible in the frontend (File API — Web APIs | MDN (mozilla.org)). However, these are all for reading and manipulating uploaded files.

Backend: Read and write files.

Using NodeJS, we have utilities for writing files.

  1. fs
  2. fs-promise

Both are similar, but you will most likely need to use fs-promise which returns a promise as its result, versus fs which takes a callback.

In this article we will focus on fs-promise.

fs promise

In this example we will use writeFile() from the File System NodeJS package. In 4 lines of code (or less) you can output a string onto your fil system. Please read the comments!

import { writeFile } from "fs/promises";
import { Buffer } from 'node:buffer';

async function myFileCreator() {

// 1. Convert your string into a NodeJS Buffer
const bufferString = Buffer.from("Hello universe!");

// 2. Convert your buffer into a Uint8Array
const content = new Uint8Array(bufferString);

// 3. Specify file name or path
const filename = "C:\Users\janac\hello.txt";

// 4. Write the file!
await fs.writeFile(filename, content);
}

The above code outputs a text file hello.txt with the content “Hello universe!”, on to my home folder at C:\Users\janac\ .

Caveats

  1. Don’t do this in production. The reason being that you typically don’t want to create files on your servers file system, since most cloud deployment providers (i.e. Vercel)…

--

--

janac

Most of my writing is about software. I enjoy summarizing and analyzing books and self-help videos. I am senior software consultant at LazerTechnologies.com.