HomeBlogWeb DevelopmentProcess of Creating Directory and Temp-directory with Node.js

Process of Creating Directory and Temp-directory with Node.js

Published
16th Oct, 2023
Views
view count loader
Read it in
8 Mins
In this article
    Process of Creating Directory and Temp-directory with Node.js

    Node.js is an open-source JavaScript runtime environment. Node.js is a cross-platform tool that is suitable for every type of project, from small to large. It runs on the V8 JavaScript engine (core of Google Chrome) which is the main reason behind the performance of Node.js. On top of that, you do not have to create individual threads for each task and can run an application in a single process, reducing the overhead.

    Node.js has become popular among front-end developers. It allows the developers to write JavaScript server-side code and the client-side code, without relying on any other language to create the project. As mentioned in this article, proper node js training will help you achieve this task with simple code.  

    It was just an introduction for those who have just started with Node.js. You can carry out various tasks that are very basic for any language. In this article, we will be discussing how you can use nodes to create a directory and temporary directory.

    Node.js offers a vast library with several modules that helps you to perform various tas efficiently and effortlessly. One of the modules is the FS core package, providing the fs.mkdir() function. This function lets you create directories or folders. The “fs” package is included within the Node.js core module, and there is no need to install the npm packages to use it. You can import npm into your code without changing any configuration. 

    Steps to Create a Directory

    Creating a directory is a straightforward task in Node.js. We have used the basic code for creating the directory in Node.js.

    For example-

    const fs = require("fs")
    fs.mkdir("./new-directory-name", function(err) {
      if (err) {
        console.log(err)
      } else {
        console.log("New directory successfully created.")
      }
    })

    Once you run this code, you will get the below output on the right side of the image.

    Output-

    IMAGE

    Now, we will see in detail what the above code does.

    The require() function in the above code will indicate that we want to use the package. In this case, we are using the “fs” package. In the following line of code, we have used the fs.mkdir() function, where we have passed the path for the new directory specifying where we want to create the directory. You can also see that there is another parameter function with an error. If any error occurs while creating the directory, it will be displayed on the screen. Even if the directory is completed successfully, you will get the success message as we have mentioned in the code.  

    fs.mkdirSync() 

    Suppose you want to check if the directory you are creating already exists or not. You can use the existsSync()method to check the existence of the directory. The mkdirSync() and existsSync()are the two different methods under the fs package.  

    • The mkdirSync() function will create the directory with the specified name within brackets.
    • The existsSync() method will check for the existence of the directory.

    The below example will help you understand the working of mkdirSync() and existsSync()methods.

    Example-  

    const fs = require('fs');
    const dir = './views';
    // create new directory
    try {
        // check if directory already exists
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir);
            console.log("Directory is created.");
        } else {
            console.log("Directory already exists.");
        }
    } catch (err) {
        console.log(err);
    }

    Output-

    IMAGE

    fs.mkdir() with recursive: true 

    All the directories, folders, and files in Node.js are stored in a tree-like structure. There are some scenarios where you need to create multiple levels of directories. But, before that, you need to make sure that any of the directories do not exist at the specific path.  

    Again, we will use the fs.mkdir() function. This function has an optional recursive parameter, which we will use to create a parent directory. To use this functionality, make sure you have Node v10.12 or above. Also, you cannot use it on the Windows platform.  

    For example-

    const fs = require("fs")
    fs.mkdir("./dir_name", { recursive: true }, function(err) {
      if (err) {
        console.log(err)
      } else {
        console.log("New directory successfully created.")
      }
    })

    Output-

    IMAGE

    Now, we will see in detail what the above code is doing. Again, we are importing the fs package using the required function and using the fs.mkdir function to create the directory. Here, we have passed three parameters- one is the directory path, the next is the recursive option to create the parent directory, and the third parameter will deal with the error that occurred.

    fsPromises.mkdir() 

    It is the promise version of the mkdir function that takes two arguments. The first argument is the path object, string, a Buffer object, or an URL object. Whereas the second argument is an object with various properties that we can set as options. This function will return a promise that works with no argument when the directory creation operation succeeds.

    For example-

    const fsPromises = require("fs").promises;
    const dirToCreate = "./createdFolder";
    (async => {
      await;
      fs.mkdir(dirToCreate, {recursive: true});
     console.log("Directory created!");
    });

    Output-

    IMAGE

    The above code will create all the parent directories for the lowest level as recursive is set to true. It is a better option than the mkdirSync() function to create directories sequentially. It is because promises module does not tie up the whole program synchronously, just like the synchronous version. If you want to learn more, you can go for the best entire full stack developer course.

    Methods to Create Temp-directory in Node.js 

    You might come across situations where you want to create temporary directories for your project. Below is the code to explain to you how to create temporary directories.

    For example-

    const fs = require('fs');
    const os = require('os');
    const path = require('path');
    let tmpDir;
    const appPrefix = 'my-app';
    try {
      tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), appPrefix));
      // the rest of your app goes here
    }
    catch (e) {
      // handle error
    }
    finally {
      try {
        if (tmpDir) {
          fs.rmSync(tmpDir, { recursive: true });
        }
      }
      catch (e) {
        console.error(`An error has occurred while removing the temp folder at ${tmpDir}. Please remove it manually. Error: ${e}`);
      }
    }

    Output-

    IMAGE

    We get the console error mentioned in the above code as an output.

    We will understand the above code, how each function and package worked here.

    First, we have imported three different packages- fs, os, and path using the required function. In the following line of code, we have defined a variable tmpDir to store the complete path to our temporary directory that we will create. As you can see, we have placed our code in the try, catch, and finally block to manage the unexpected errors while running the code. Here, the purpose of using the try..catch block is that we will delete the folder when it is not required anymore.  

    We have created a temp directory in the first try block. We then used the os.tmpdir() function that is a part of the os package. It will provide you the location of the system temp folder. Then, we have combined the location with a prefix using the path.join() function. It is up to you if you want to use this function as it is optional, but it will help you locate the temp directory whenever required.  

    Now, you can see that we have used the fs.mkdtempSync() function for adding a random string to the specified prefix and creating a folder on that path.  

    These temp directories will exist until you delete them manually or via code. So, make it a good practice to delete the temp directories once they serve their purpose of freeing up unnecessary space. To delete the temp directory, we have to use the logic to try, catch..finally, statement—the actual code for deleting goes in try. If case of any error, the catch block will handle it. Then comas the Finally block that will be executed whether the code execution fails.  

    The code mentions the fs.rmSync(tmpDir, { recursive: true }). Sometimes, deleting the temp directory may fail and you have to delete it manually.

    fs.mkdtemp()

    The fs is one of the core packages in Node.js. It comes with many functions and methods that have made it easier to perform specific tasks. One of those functions is mkdtemp(), used for creating a unique type of temporary directory. For creating the folder's name, you need to append six randomly generated characters behind a prefix string. You can also create a temporary directory inside a folder with the help of a separator after the folder path.

    Below is the syntax of mkdtemp() function.

    fs.mkdtemp( prefix, options, callback )

    Where,

    • Prefix: Use the prefix before the six randomly generated numbers of the directory that you will create.
    • Options: It can be a string or an object with encoding property. This is used to specify the character encoding to be used.
    • Callback: this function will be called when the method is executed.
      • err: specifies the error that will be thrown in case of the failed operation.
      • folder refers to the temporary folder path you will create with the function.

    For example-

    const fs = require('fs');
    fs.mkdtemp("temp-", (err, folder) => {
      if (err)
        console.log(err);
      else {
        console.log("The temporary folder path is:", folder);
      }
    });

    Output-

    IMAGE

    The above code will help you create a temporary directory with the prefix “temp-” in the current directory.

    fs.mkdtempSync() 

    Another function of the fs package is an inbuilt application programming interface, providing an API and allowing you to interact with the file system similar to standard POSIX functions. You can also consider it a synchronous version of the fs.mkdtemp() method described above. You can create a unique temporary directory with the fs.mkdtempSync() function.

    Below is the syntax for fs.mkdtempSync() function-

    fs.mkdtempSync( prefix, options )

    Where,

    • Prefix: prefix: make sure to use the prefix before the six randomly generated numbers of the directory that you will create.
    • Options: It is an optional string parameter, used for the encoding or an object with an encoding property.

    For example-

    const fs = require("fs");
    const prefix = "./tempDir";
    try {
      const folder = fs.mkdtempSync(prefix, {
        encoding: "utf8"
      });
      console.log("Temp directory created!", folder);
    } catch (error) {
      console.error(error);
    }

    Output-

    IMAGE

    Creating Temp-directory in Node Without JavaScript 

    For creating the temporary directory within the Node.js without using JavaScript, make sure that you complete the temporary directory in the /tmp folder..

    Looking to kickstart your coding journey? Discover the best Python course online for beginners. Unleash your potential with Python's versatility and power. Join now!

    Conclusion

    Node.js is the most commonly used JavaScript runtime for both client-side and server-side programming. Due to this reason, it is a highly preferred environment among developers to create even critical applications. Node.js provides standard libraries including several functions and packages that you can include to make your work easier. One of those tasks is creating directories and temporary directories. Node.js provides a specific package for that, mentioned in this article.

    Whether you are a beginner or an experienced professional, you will always have to create directories or temporary directories for your project. Go through this article to understand the detailed working of the primary directory creation code. For a better learning approach, you can consider KnowledgeHut node.js training.    

    Frequently Asked Questions (FAQs)

    1How can I create a directory in Node.js?

    In Node.js, you can use either of the functions under the /”fs” package- fs.mkdir() or fs.mkdirSync() or fsPromises.mkdir().  

    2How can I create a temp directory in Node.js?

    Like creating directories in node.js, you can also create temporary directories using different functions of the “fs” package or module- Fs.mkdtemp, fs.mkdtempSync, and fsPromises.mkdtemp.

    3How can I create a temp directory in Linux?

    For creating a temporary directory in Linux, you can use its mktemp utility. With this utility, you can create the directory effortlessly. You can also provide the complete path after the “mktemp” to specify where you want to create the temp directory. By default, if you do not mention the specific path, the folder will get started in the/tmp folder.

    mktemp /tmp/directory_name
    4What is the process of creating a directory in JS?

    Below is the process-

    • Import the required package- “fs”.
    • you can use either of the functions under the /”fs” package- fs.mkdir() or fs.mkdirSync() or fsPromises.mkdir().
    • Delete the temp directory once the work is done.
    5How can I create a temp directory in bash?

    You can create the temp directory in bash using the syntax of the following “mktemp” command.

    mktemp -d -t ci-XXXXXXXXXX

    Where d will specify to create the directory, it will select the template in which you want to make the temp directory. The X character will be replaced by any random character. For example-

    #!/bin/bash
    tmp_dir=$(mktemp -d -t ci-XXXXXXXXXX)
    echo $tmp_dir
    # ...
    rm -rf $tmp_dir
    Profile

    Aashiya Mittal

    Author

    Aashiya has worked as a freelancer for multiple online platforms and clients across the globe. She has almost 4 years of experience in content creation and is known to deliver quality content. She is versed in SEO and relies heavily on her research capabilities.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon