Categories
JavaScript Nodejs

Node.js FS Module — Truncating and Removing Files

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 basic feature. Fortunately, Node.js has a fs module built into its library. It has many functions that can help with manipulating files and folders. File and directory operation 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 have 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 truncate files with the truncate family of functions and remove files and symbolic links with the unlink family of functions.

Truncate Files with the fs.truncate Family of Functions

We can truncate files with the Node.js truncate family of functions. Truncating a file is to shrink the file to a specified size. To truncate a file asynchronously we can use the truncate function. The function takes 3 arguments. The first argument is the path object, which can be a string, a Buffer object or an URL object. When a file descriptor is passed into the first argument instead of the path, it will automatically call ftruncate to truncate the file with the given file descriptor. Passing in a file descriptor is deprecated and may thrown an error in the future. The second argument is the length of the file in bytes that you want to truncate it to. The default value is 0. Any extra data bigger than the size specified is lost when the size is smaller than the original size. The third argument is a callback function that is run when the truncate operation ends. It takes an err parameter which is null when the truncate operation succeeds and has an object with the error information otherwise.

To truncate a file with the truncate function, we can write the following code:

const fs = require("fs");  
const truncateFile = "./files/truncateFile.txt";

fs.truncate(truncateFile, 1, err => {  
  if (err) throw err;  
  console.log("File truncated");  
});

If we run the code above, there should be a single byte of content left in the file you’re truncating.

The synchronous version of the truncate function is the truncateSync function. The function takes 2 arguments. The first argument is the path object, which can be a string, a Buffer object or an URL object. When a file descriptor is passed into the first argument instead of the path, it will automatically call ftruncateSync to truncate the file with the given file descriptor. Passing in a file descriptor is deprecated and may thrown an error in the future .The second argument is the length of the file in bytes that you want to truncate it to. The default value is 0. Any extra data bigger than the size specified is lost when the size is smaller than the original size. It returns undefined .

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

const fs = require("fs");  
const truncateFile = "./files/truncateFile.txt";

try {  
  fs.truncateSync(truncateFile, 1);  
  console.log("File truncated");  
} catch (error) {  
  console.error(error);  
}

If we run the code above, there should be a single byte of content left in the file you’re truncating.

There’s also a promise version of the truncate function. The function 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 the length of the file in bytes that you want to truncate it to. The default value is 0. Any extra data bigger than the size specified is lost when the size is smaller than the original size. It returns a promise that is resolved with no arguments when the operation is successful.

To truncate a file with the promise version of the truncate function, we can write the following code:

const fsPromises = require("fs").promises;  
const truncateFile = "./files/truncateFile.txt";

(async () => {  
  try {  
    await fsPromises.truncate(truncateFile, 1);  
    console.log("File truncated");  
  } catch (error) {  
    console.error(error);  
  }  
})();

If we run the code above, again there should be a single byte of content left in the file you’re truncating.

Remove Files and Symbolic Links with the fs.unlink Family of Functions

We can remove a file or a symbolic link with the unlink function. The function 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 a callback function that takes an err object, which is null when the file or symbolic link removal operation succeeds, and has the error data if the operation failed. The unlink function doesn’t work on directories in any state. To remove directories, we should use the rmdir function.

To use the unlink function to remove a file, we can something like the code below:

const fs = require("fs");  
const fileToDelete = "./files/deleteFile.txt";

fs.unlink(fileToDelete, err => {  
  if (err) {  
    throw err;  
  }  
  console.log("Removal complete!");  
});

If we run the code above, the file that’s to be deleted should be gone.

The synchronous version of the unlink function is the unlinkSync function. The function takes one argument. The only argument is the path object, which can be a string, a Buffer object or an URL object. It returns undefined .

We can use it like in the following code:

const fs = require("fs");  
const fileToDelete = "./files/deleteFile.txt";

try {  
  fs.unlinkSync(fileToDelete);  
  console.log("Removal complete!");  
} catch (error) {  
  console.error(error);  
}

There’s also a promise version of the unlink function. The function takes one argument. The only argument is the path object, which can be a string, a Buffer object or an URL object. It returns a promise that’s resolved with no argument when the operation is successful.

If we run the code above, the file that’s to be deleted should be gone.

We can use it like in the following code:

const fsPromises = require("fs").promises;  
const fileToDelete = "./files/deleteFile.txt";

(async () => {  
  try {  
    await fsPromises.unlink(fileToDelete);  
    console.log("Removal complete!");  
  } catch (error) {  
    console.error(error);  
  }  
})();

If we run the code above, the file that’s to be deleted should be gone.

The promise version of the unlink function is a much better choice than the unlinkSync function when you want to do multiple things sequentially that includes a call to the unlink function since it doesn’t tie up the whole program waiting for the file or symbolic link deletion operation to complete before continuing to program other parts of the program.

In this article, we truncate files with the truncate family of functions and remove files and symbolic links with the unlink family of functions. The truncate family of functions let us specify the number of bytes to keep while truncating the rest of the file. The unlink family of functions remove files and symbolic links. If we want to do these operations sequentially with other operations, the promise versions of these functions. Even though the API is still experimental, it is much better than the synchronous versions of these functions since it allows for sequential and asynchronous operations with promises. Also, it helps avoid callback hell where we nest promises in too many levels.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.