Node: Check if File or Directory is Empty

Introduction

Web applications typically receive user input in some form - and with any input, validation is important. Making sure that form fields contain valid data, or that they contain any data at all is one of the first checks you can do.

When a user uploads files - you'll want to check whether these files are empty, not just if they exist or not. Additionally, since Node supports server-side development and can work with the file system, you'll find yourself working with files and directories all the time, especially if you're creating a CLI application.

In this guide, we'll take a look at how to check if a file or directory is empty, using Node.js.

Note: This task can be observed through two lenses - receiving a file from the front-end and validating it, or working with the file system regardless of potentially non-existent front-end. We'll be taking a look at both.

Check if a File is Selected With JavaScript

Vanilla JavaScript isn't up for the task of checking whether a file is empty or not, since it can check whether a form has a file attached to it, but can't process the file itself.

We'll start from there - checking if the file is selected from the file system and attached to the form. Let's create a simple form on the front-end

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Meta tags -->
</head>
<body>
    <form enctype="multipart/form-data">
        <input type="file" name="file" id="file">
        <button type="submit" onclick="checkFile()">Submit</button>    
    </form>
        
    <script src="script.js"></script>
</body>
</html>

The page contains a <form> that accepts a multipart file, through an <input type="file">. Once the button is pressed, the checkFile() function is triggered, from the imported script.js:

function checkFile() {
    let fileInputField = document.getElementById("file");
    if (fileInputField.files.length == 0) {
        alert("Please select a file!")
    }
}

We get our input element with document.getElementById() and check the length of the files property, which an input of type file has. If it's empty, we alert the user that no file has been selected.

Once we're sure that the user has supplied a file, we can check whether they've supplied a non-empty file.

The fs Module

Node.js is a JavaScript runtime environment that executes JavaScript code outside of the browser. This gives us the ability to interface with the underlying operating system and file system as well. The built-in fs (File System) module works wonders for us in this case.

We'll be relying on the fs.readFile() and fs.readdir() methods.

Check if a File is Empty with Node.js

Once the user sends a file through a form to your back-end, say, to the /upload endpoint, it's time to check whether the file is empty.

The easiest way to check is to stream the data within the file and check its length. If there are 0 bytes in the file, or rather, if the length of the data is equal to 0, the file is empty:

router.post('/upload', function(req, res) {
    const fs = require('fs');
    const multiparty = require('multiparty');
    let form = new multiparty.Form();
    form.parse(req, function(err, fields, files) {
        let file = files.keySelect[0];
        fs.readFile(file, function(err, data) {
            if (data.length == 0) {
                return res.status(422).json({message : "File is empty! Unprocessable Entity."});
            }
        })
    });
    return res.status(200).json({message: "Success"});
});

We've used the multiparty module to obtain the file from the form, though, this step can be done with various other libraries as well, such as Multer or Formidable.

With multiparty, we can create an instance of a form and parse it, passing the req to it, which is our formData sent from the front end. The keySelect() method returns all files sent via the form, but since our form only accepts one and we're only expecting one - we're accessing it via [0]. Using the fs.readFile() method, we're reading the file and unpacking its data. If this data has a length of 0 - the file is empty, and we return a “422 Unprocessable Entity” status code.

If you're not dealing with a form-provided file, and already have the name in mind, you can skip this process entirely and read the file directly:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

fs.readFile("myFile.txt", function(err, data) {
    if (data.length == 0) {
        console.log("File is empty!");
    } else {
        console.log("File is not empty!");
    }
})

Check if a Directory is Empty with Node.js

When checking if a directory is empty, we can use the readDir() method:

fs.readdir(directoryName, function(err, data) {
    if (data.length == 0) {
        console.log("Directory is empty!");
    } else {
        console.log("Directory is not empty!");
    }
})

These two methods are completely equivalent in syntax (except for the name of the method), so everything that applies to one, applies to the other. If the data of the directory is equal to 0, it's empty.

This is typically coupled with listing files in a directory.

Conclusion

Working with files is commonplace for Node projects, as it's meant to be used on the server-side. One of the basic checks you can perform to validate files is to check whether they're empty or not.

In this guide, we've taken a look at how to check if a file or directory is empty with Node.js.

Last Updated: October 14th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Project

React State Management with Redux and Redux-Toolkit

# javascript# React

Coordinating state and keeping components in sync can be tricky. If components rely on the same data but do not communicate with each other when...

David Landup
Uchechukwu Azubuko
Details

Getting Started with AWS in Node.js

Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms