#100DaysOfMERN - Day 55

#100DaysOfMERN - Day 55

·

4 min read

✏ File System API

A short post about how to use Node's File System API.

I'm busy building my private Radio MERN App, and while the frontend is already in place, the two biggest remaining tasks are:

  • user authorisation/authentication

  • building the database

I'm currently dealing with the latter, which breaks down to: adding all song titles from my harddrive, with a whole bunch of related data like author, year, genre and whatever else you want to add, but most importantly, the filename and folder of the actual audio file.

Copying/pasting those for all songs would be pure madness, but conveniently, Node comes with a very handy File System API. I've already encountered it on

  • Day 18: How to read from / write to a .json file

  • Day 22: How to serve static HTML files

Since it's a core module of Node, there's no need to install it, just require/import:

const fs = require('fs')

The API is huge, so this post is only about the parts that I used for the tasks at hand. Plus I accidentally found out that it's dead simple to use it to stream audio files from a Vanilla server, so I'll add that code at the very bottom ↓


Check operation permissions

Before working on a file, let Node check if it has access and necessary permissions withfs.access. The second parameter defines what you'd like to check:

  • fs.constants.F_OK: file exists

  • fs.constants.R_OK: file exists and reading permission

  • fs.constants.W_OK: file exists and writing permission

  • fs.constants.X_OK: file exists and execution permission

const filePath = 'C:/folder/file.ext';

fs.access(filePath, fs.constants.F_OK, err => {
    console.log(err ? err : 'Good To Go');
});

Reading files

fs.readFile(filePath, (err, data) => {
    console.log(err ? err : data);
});

This will log the data in a Buffer format. If you want to read a text file, add utf-8 as encoding parameter:

fs.readFile(filePath, 'utf-8', (err, data) => {
    console.log(err ? err : data);
});

Note: Reading an audio file and logging it with utf-8 floods your console

Reading filenames from directory

Reading directories works the same as reading files:

const folderPath = 'C:/folder';

fs.readdir(folderPath, (err, data) => {
    console.log(err ? err : data);
});

This will log an array with all file names and subfolders in that folder.

Renaming files

Easily enough, all it requires is the current filename (including full absolute path) and the new one:

const currPath = 'C:/folder/filename.mp3';
const newPath = 'C:/folder/new-filename.mp3';

fs.rename(currPath, newPath, err => {
    console.log(err ? err : 'file renamed');
});

Moving files

This can also be done with fs.rename (changing the path will actually move the file there):

const currPath = 'C:/folder/filename.mp3';
const newPath = 'C:/new-folder/new-filename.mp3';

fs.rename(currPath, newPath, err => {
    console.log(err ? err : 'file renamed and moved');
});

I think these are all the functions I'll need to handle the files for my database. Note that I've consistently used the asynchronous versions (all file operations are asynchronous by nature), so they all require a callback. Most functions have a synchronous equivalent though (renameSync instead of rename, readFileSync instead of readFile).


✏ Create Audio Stream from Vanilla Server

Little experiment for fun, building on the code from Day 21: How to Set Up a Vanilla JS Server. Going to localhost:3000/music will send the stream to the browser:

import http from 'http';
import fs from 'fs';

const app = http.createServer((req, res) => {

    if (req.url === '/music') {
        const fileName = 'music.mp3';
        const stream = fs.createReadStream(fileName);

        stream.on('open', function () {
            stream.pipe(res);
        });

        stream.on('error', function (err) {
            res.end(err);
        });
    }
});

app.listen(3000, () => console.log('server is running on port 3000'));

✏ Ressources

nodejs.dev/learn: The Node.js fs module

NodeJS File System API: beginner-friendly guide


✏ Thanks for reading!

I do my best to thoroughly research the things I learn, but if you find any errors or have additions, please leave a comment below, or @ me on Twitter. If you liked this post, I invite you to subscribe to my newsletter. Until next time 👋


✏ Previous Posts

You can find an overview of all previous posts with tags and tag search here:

#100DaysOfMERN - The App