Categories
JavaScript Nodejs

Node.js FS Module — Creating Directories

Spread the love

Manipulating files and directories are basic operations for any program. Since Node.js is a server-side platform and can interact with the computer that it’s running on directly, being able to manipulate files is a core feature.

Fortunately, Node.js has the fs module built into its library. It has many functions that can help with manipulating files and folders. File and directory operations that are supported include basic ones like manipulating and opening files in directories.

Likewise, it can do the same for files. It can do this both synchronously and asynchronously. It has an asynchronous API that has functions that support promises.

Also, it can show statistics for a file. Almost all the file operations that we can think of can be done with the built-in fs module. In this article, we will create directories with the mkdir and mkdtemp family of functions to create normal directories and temporary directories respectively.

Creating Permanent Directories with fs.mkdir Family of Functions

To create permanent directories, we can use the mkdir function to create them asynchronously. It takes 3 arguments. The first argument is the path object, which can be a string, a Buffer object or an URL object.

The second argument is an object with various properties that we can set as options.

The recursive property is a boolean property that lets us create all the levels of the directory if not all the levels exist. The default value of the recursive property is false .

The mode property is an octal number property that we set the directory’s permission and sticky bit for POSIX systems. This option isn’t supported on Windows.

The default value for mode is 0o777 , which is readable, writable and executable for everyone.

The mode integer can also replace the options object as the second argument. The third argument is a callback function which is called when the directory creation operation is complete.

The function takes an err parameter which is null when the operation succeeds and has an object with the error information otherwise.

Calling mkdir when the path is a directory that exists results in an error only when the recursive option is set to false .

We can use the mkdir function like in the following code:

const fs = require("fs");  
const dirToCreate = "./files/createdFolder/createdFolder";

fs.mkdir(  
  dirToCreate,  
  {  
    recursive: true,  
    mode: 0o77  
  },  
  err => {  
    if (err) {  
      throw err;  
    }  
    console.log("Directory created!");  
  }  
);

If we run the code above, we can see that it created all the parent directories for the lowest level directories since we set recursive to true .

The synchronous version of the mkdir function is the mkdirSync function. It takes 2 arguments. The first argument is the path object, which can be a string, a Buffer object or an URL object.

The second argument is an object with various properties that we can set as options. The recursive property is a boolean property that lets us create all the levels of the directory if not all the levels exist. The default value of the recursive property is false .

The mode property is an octal number property that we set the directory’s permission and sticky bit for POSIX systems.

This option isn’t supported on Windows. The default value for mode is 0o777 , which is readable, writable and executable for everyone. The mode integer can also replace the options object as the second argument. The function returns undefined .

Calling mkdir when the path is a directory that exists results in an error only when the recursive option is set to false .

We can use the mkdirSync function like in the following code:

const fs = require("fs");  
const dirToCreate = "./files/createdFolder/createdFolder";

fs.mkdirSync(dirToCreate, {  
  recursive: true,  
  mode: 0o77  
});  
console.log("Directory created!");

If we run the code above, we can see that it created all the parent directories for the lowest level directories since we set recursive to true .

There’s also a promise version of the mkdir function. . It takes 2 arguments. The first argument is the path object, which can be a string, a Buffer object or an URL object.

The second argument is an object with various properties that we can set as options. The recursive property is a boolean property that let us create all the levels of the directory if not all the levels exist. The default value of the recursive property is false .

The mode property is an octal number property that we set the directory’s permission and sticky bit for POSIX systems. This option isn’t supported on Windows.

The default value for mode is 0o777 , which is readable, writable and executable for everyone. The mode integer can also replace the options object as the second argument.

The function returns undefined . Calling mkdir when the path is a directory that exists results in a promise reject only when the recursive option is set to false .

The function returns a promise that resolves with no argument when the directory creation operation succeeds.

We can use the promise version of the mkdir function like in the following code:

const fsPromises = require("fs").promises;  
const dirToCreate = "./files/createdFolder/createdFolder";

(async () => {  
  await fsPromises.mkdir(dirToCreate, {  
    recursive: true,  
    mode: 0o77  
  });  
  console.log("Directory created!");  
})();

If we run the code above, we can see that it created all the parent directories for the lowest level directories since we set recursive to true . This is a better option than using mkdirSync for creating directories sequentially since it doesn’t tie up the whole program like the synchronous version does when the directory creation operation is being run.

Creating Temporary Directories with fs.mkdtemp Family of Functions

The Node.js fs module has special functions for creating temporary directories. The mkdtemp family of functions allows us to do this with one function call.

The mkdtemp function takes 3 arguments. The first argument is the prefix for the temporary folder which is a string. It’s the path of the folder that you want to create, which will have some characters appended to it. The second argument is an options string or object.

The options object consists of the encoding property which is the character encoding for the folder name, which defaults to utf8 .

The encoding value string can replace the object as the second argument. The second argument is optional.

The third argument is a callback function that is called when the temporary directory creation function ends.

The callback function has 2 parameters. The first one is the err object which is null when the operation succeeds. The second parameter is the folder path which is a string.

The folder name for the generated folder will have the prefix with 6 random characters appended behind the prefix. In some systems like BSD systems, it can return more than 6 random characters after the prefix.

If we want to create a temporary directory within /tmp , then the prefix must end with a platform-specific path separator, which we can get from require(‘path’).sep .

We can create a temporary directory with the following code:

const fs = require("fs");  
const prefix = "./files/tempDir";

fs.mkdtemp(  
  prefix,  
  {  
    encoding: "utf8"  
  },  
  (err, folder) => {  
    if (err) {  
      throw err;  
    }  
    console.log("Temp directory created!", folder);  
  }  
);

If we run the code, we get the folder path logged in the console.log and we should see a new temporary folder created in the given path.

The mkdtemp function has a synchronous counterpart called the mkdtempSync function. The mkdtemp function takes 2 arguments. The first argument is the prefix for the temporary folder which is a string.

It’s the path of the folder that you want to create, which will have some characters appended to it.

The second argument is an optional string or object. The options object consists of the encoding property which is the character encoding for the folder name, which defaults to utf8 .

The encoding value string can replace the object as the second argument. The second argument is optional. It returns the created folder path.

If we want to create a temporary directory within /tmp , then the prefix must end with a platform-specific path separator, which we can get from require(‘path’).sep .

We can use the mkdtempSync function like in the following code:

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

If we run the code, we get the folder path logged in the console.log and we should see a new temporary folder created in the given path.

There’s also a promise version of the mkdtemp function. The mkdtemp function takes 2 arguments. The first argument is the prefix for the temporary folder which is a string.

It’s the path of the folder that you want to create, which will have some characters appended to it. The second argument is an optional string or object.

The optional object consists of the encoding property which is the character encoding for the folder name, which defaults to utf8 .

The encoding value string can replace the object as the second argument. The second argument is optional.

It returns a Promise that resolves with the path of the created directory when the temporary directory creation operation succeeds.

If we want to create a temporary directory within /tmp , then the prefix must end with a platform-specific path separator, which we can get from require(‘path’).sep .

We can use the promise version of the mkdtemp function like in the following code:

const fsPromises = require("fs").promises;  
const prefix = "./files/tempDir";

(async () => {  
  try {  
    const folder = await fsPromises.mkdtemp(prefix, {  
      encoding: "utf8"  
    });  
    console.log("Temp directory created!", folder);  
  } catch (error) {  
    console.error(error);  
  }  
})();

If we run the code, we get the folder path logged in the console.log and we should see a new temporary folder created in the given path. This is a better option than using mkdtempSync for creating directories sequentially since it doesn’t tie up the whole program like the synchronous version does when the directory creation operation is being run.

We created permanent directories with the mkdir family of functions to create normal directories. The mkdir family of functions can create all the parent directories along with the actual directory that we can create.

Also, we created temporary directories with the mkdtemp family of functions.

There’re the regular callback-based asynchronous function, the new promised basic asynchronous function, and the synchronous version of each function.

This promise versions of the functions are better creating directories sequentially since it doesn’t tie up the whole program like the synchronous version does when the directory creation operation is being run.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.