Node JS Get All Files In Directory Example

This example will show you how to implement an http server that gets all the current directory’s child folders and files and return the related data in the JSON format string.  It will tell you how to use the Node JS http, fs module.

1. Node JS Read Directory Child Files Example.

  1. There are two js files and two folders under the http web server root folder. And one of the folders is a hidden directory.
    .idea            --- directory
    example          --- directory
    file-operator.js --- file
    http-server.js   --- file
  2. As you can see in the above files list, the http-server.js file is just the javascript file that will create an http web server and listen on port 8888. The file-operator.js js file is a module that provides the get child files list function under the provided parent folder. You should execute http-server.js to run this example.
  3. When you execute the example and browse url http://localhost:8888/ in a web browser, you can see the below content in the web page.

2. Http-Server Node JavaScript File.

  1. http-server.js
    /* Require http module to create http web server.*/
    var http = require('http');
    /* file-operator module is used to get all child dirs of files of parent folder.*/
    var file_operator = require('./file-operator');
    // Global variable for request and response object.
    var request = null;
    var response = null;
    /* Call back function that is invoked when server receive a client request.*/
    var http_request_callback =  function (req, resp) {
        // Initialize global request and response object.
            request = req;
            response = resp;
        // Print log in console.
        console.log("Server receive request.");
        console.log("Request method : " + req.method);
        console.log("Request url : " + req.url);
        // Assign current directory as parent folder name..
        var parent_file_name = ".";
        /* Call file_operator module function to get child folders and files of parent folder.
        *  Pass parent folder name and caller_callback function as input parameter.
        *  caller_callback function will be called in get_child_file_list function.
        *  */
        file_operator.get_child_file_list(parent_file_name, caller_callback);
    // Create http server with above callback function.
    var http_server = http.createServer(http_request_callback);
    // Http server listen on port 8888.
    /* This function is a callback function, it is used in file_operator.get_child_file_list() function. */
    function caller_callback(error, files){
        // Define response http status code.
        var resp_status_code = 200;
        // Response mime type is json string, this is set in http header.
        var resp_header_mime_type = {"Content-Type":"application/json"};
            // If read files error.
            resp_status_code = 503;
            response.writeHead(resp_status_code, resp_header_mime_type);
            // Return error message as a json string.
            // If read files successful.
            var resp_status_code = 200;
            response.writeHead(resp_status_code, resp_header_mime_type);
            // Return data is also a json object.
            var return_data = {error : null, data : { files : files}};
            // Return file names in a json string.

3. File-Operator JavaScript File.

  1. file-operator.js
    /* This module is used to get and return example files absolute path
       and check whether the file is a directory or not.*/
    // use fs module.
    var file_system = require('fs');
    // Save external caller callback function.
    var caller_callback_function = null;
    // Save parent directory name.
    var parent_folder = null;
    /* Export get_child_file_list function to outer invoker.
    *  The input parameter is the parent folder name and external caller callback function name.
    * */
    exports.get_child_file_list = function (parent_directory_name, caller_callback) {
        if(parent_directory_name!=null && parent_directory_name!='')
            // Save parent folder.
            parent_folder = parent_directory_name;
            // Save outer invoker function
            caller_callback_function = caller_callback;
            // Call fs module readdir function to read all child files under parent directory.
            file_system.readdir(parent_directory_name, readdir_callback)
    /* This is the fs module readdir function callback method. */
    function readdir_callback(error, files)
            error = null;
            var file_info_array = [];
            get_file_info_iterate(error, files, 0, file_info_array);
    /* This method is used to check whether the file is a directory or not. */
    function get_file_info_iterate(error, files, file_index, file_info_array) {
        if (file_index == files.length) {
            /* Invoke the external callback method only when all files has been calculated.*/
            caller_callback_function(error, file_info_array);
        } else {
            // Get current file by index.
            var file = files[file_index];
            // Get absolute file path.
            var file_absolute_path = parent_folder + "/" + file;
            // Save whether current file is a directory or not.
            var is_directory = false;
            // fs module's stat method is used to get file related information.
            file_system.stat(file_absolute_path, function (err, stats) {
                // If this file is a directory.
                if (stats.isDirectory()) {
                    is_directory = true;
                // Put a json string in file info array object.
                file_info_array.push({"path": file_absolute_path, "is_dir": is_directory});
                // Get next file related data in files object.
                get_file_info_iterate(error, files, file_index, file_info_array);

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.