Write to Files in Node.js: How to Guide with Examples

Read it in 7 Mins

Published
15th Feb, 2023
Views
777
Write to Files in Node.js: How to Guide with Examples

Node. js is a framework for developing efficient and scalable network approaches based on Chrome's JavaScript engine. Due to its lightweight, high effectiveness, and non-blocking I/O mechanisms, Node.JS has become a perfect choice for real-world information applications.

Out of the different stand-out functionalities and offerings, the ability to read and write files is excellent. It is a robust feature offered by NodeJS and extremely simple to implement. A file can be read or written synchronously or asynchronously from your computer. For more information, check out Full Stack learning course.  

This guide will introduce you to node.js and its modules covered in the node js program. With the help of an example, we will read, write and append JS files, which will help us understand node.js better. Also, troubleshooting tips and tricks will also be discussed at the end of this tutorial. 

The built-in fs module allows node js to write files programmatically. The module's name (fs) is an abbreviation for "file system," and it contains all of the functions required to read, write, and delete files on the local machine. Because of this distinguishing feature of nodejs write JSON to file, JavaScript is a functional language for back-end and CLI tool programming.

We can encode any JavaScript string with the node fs writefile. UTF-8 is a popular encoding for web pages and other documents. The character set used for the file's contents is called file encoding. Encodings that are commonly used include 'utf8', 'ASCII', 'binary', 'hex', 'base64', and 'utf16le'. 

Most significantly, the nodejs write to file and read on the local file system is excellent. Leverage these capabilities for logging, exporting and importing data from JSON and XML files, transferring data from one location to another, etc.

What is Node.Js ‘fs’ module?

‘fs’ Module is inbuilt provided by Node.js to perform different actions. The ‘fs’ Module is a file system module that helps you work with files, like read files, write files, append files, and many more. It operates both, synchronously and asynchronously. Let's look at an example of how to use the fs module. 

const fs = require('fs') 

Instead of var we will use const which is ES6 feature. This will need the built-in module from Node.Js, and it will be ready to use. 

Some functionalities of the fs module include 

  1. unlinkSync: The unlinkSync is intended to delete files synchronously. 
  2. unlink: Like unlinkSync, the unlink function is used to delete files asynchronously. The parameters of unlink are the path to the file to be deleted and a callback function. When deleting fails, the callback function returns the error. If it is deleted, it displays a message indicating that it was successfully deleted. 
  3. readFile: We use the readFile function to read files asynchronously. The path location and a callback function are given as parameters. 
  4. readFileSync: We use the readFile Sync function to read files synchronously in order. The path of the file is taken as a parameter. 
  5. writeFile: The writeFile function is used to write js files asynchronously. The fileName, textToBeWritten, FileEncodingType, Callback functions are taken as input parameters. 
  6. writeFileSync: The node writeFileSync function is used to write into files synchronously. The fileName, inputText and file-encoding functions are taken as input parameters. 
  7. stats.isDirectory: When there is a need to verify whether a file exists or not, we use the function stats.isDirectory. It returns a boolean value. 

The ‘fs’ module provides both asynchronous and synchronous options. 

  • The synchronous option prevents the code from running till the file action is performed. 
  • The asynchronous option does not prevent code from running. It calls a callback function after the file operation is finished. 

Are you interested to explore more node.js modules? Check out the java full stack developer course from Knowledgehut and step forward with your learning journey. 

Reading from Node.js Files

There are two methods to read a file in node.js. We will see both of them. 

1. Reading file Asynchronously

Another perk of using node.js is the option for js write to a json file. Reading a file asynchronously is the simplest way to read the file using fs.readFile() function. It is non-blocking because it doesn’t block the rest of the code while executing.

As you know, basic JavaScript functions and this asynchronous function are features of JavaScript. This readFile() function takes two arguments, one argument will define our file path and the second argument is a callback function. 

const fs = require('fs'); 
fs.readFile('file.txt', (err, data) => { 
if(err) { 
throw err; 
} 
console.log(data.toString()); 
}); 

Callback Function will be called with two arguments, one is error and another is data; where data is the file content and the err object contains information of runtime errors. 

2. Reading file Synchronously

The second way of reading a file is using the synchronous version of fs.readFile() which is known as fs.readFileSync(). It also takes the two arguments, the first one is the path of the file and the other is character encoding. If character encoding is not used then the output will be shown as a buffer.

You can also omit printing buffer in the terminal by specifying the file encoding as the second parameter after the file path: 

const fs = require('fs'); 
try{ 
const data = fs.readFileSync(file.txt); 
console.log(data.toString()); 
} catch (err) { 
console.error(err); 
} 

Before calling the callback function both the functions fs.readFIle() and fs.writeFile() read the full contents of the file in memory. As a result, it may affect memory usage and application execution whenever you read a huge file. 

Writing to Node.Js Files

Use the handy writeFile method inside the standard library's fs module to save strenuous efforts and time. 

Let’s understand each term in detail: 

  1. file = (string): The file path of the file and it allows to write. 
  2. data = (string or buffer): The data you want to write to the file. 
  3. encoding = (optional string): The encoding of the data 
  4. callback = (optional function (err) {}): If there is no error, err === null, otherwise err contains the error message. 

Like we have two methods for reading to Node.js Files, we also have two methods for writing to Node.Js Files.

1. Writing file Asynchronously 

For writing a file asynchronously, we need to use the fs.writeFile() function. It will follow the same process that we followed in the reading file asynchronously. Instead of read we will use fs.writeFile(). It is the easiest way to write data files in Node.Js. This function takes three arguments - the file name, the data to write, and a callback function. The callback() function only accepts one argument for error handling in this case. 

const fs = require('fs'); 
const data = "This is the new content of the file."; 
fs.writeFile('file.txt', data, (err) => { 
if(err) { 
throw err; 
console.log("Data has been written to file successfully."); 
}); 

Our file has been successfully created using the text that we specified previously. This is how you can use NodeJS to read and write files asynchronously. 

2. Writing file Synchronously

For writing a file synchronously we need to use the function fs.writeFileSync() function. It will follow the same process that we followed in the reading file synchronously. Instead of read, we will use fs.writeFileSync(). 

const fs = require('fs'); 
const data = "This is the new content of the file."; 
try { 
fs.writeFileSync('file.txt', data); 
console.log("File has been saved."); 
} catch (error) { 
console.error(err); 
} 

If the file already exists, these methods override its contents by default. You should give a flag as the third option if you want to append data to the file: 

const fs = require('fs'); 
const data = "Append this data at the end of the file."; 
fs.writeFile('file.txt', data, {flag: 'a+'}, (err) => { 
if (err) { 
throw err; 
} 
console.log("File is updated."); 
}); 

Some of the flag options are as follows:

Flags Description
rOpens file for reading.  
  • Throws an exception if the file is found missing or doesn’t exist.
r+Open file for reading and writing.
  • Throws an exception if the file is found missing or doesn’t exist.
rsThis flag opens the file for reading in synchronous mode.

openw

Open file for writing.  
  • The file is created (if it doesn’t exist) or deleted(if it exist).
wxSimilar to the ‘w’ flag, but it will fail if the path exists.
w+Open file for reading and writing.  
  • The file is created (if it doesn’t exist) or deleted(if it exist).
w++It iss similar to ‘w+’ but it will fail if the path exists.

Both of these approaches continue writing to the file until the full contents have been written. If a lot of data is to be written, it could slow down your application. So in that scenario, using a stream for writing to huge files would be a preferable option. 

Appending to Files

To append data the fs.appendFile() method is used to a file asynchronously (and fs.appendFileSync() for synchorus). If the file does not exist, it is created. To change the behaviour of the operations the options parameter can be used. To kick-start your career in web design, enroll in Best Courses for Web Design by KnowledgeHut.  

Syntax for appending to files is: 

fs.appendFile(path, data[,options], callback) 

This method accepts four parameters as mentioned above, they are described below: 

  • Path - Path is a string, Buffer URL or integer that represents the added filename or file descriptor. 
  • data - The data to be appended is represented by a String or a Buffer. 
  • options - It’s a string or object that can be used to specify optional output parameters. It contains three settings that can be changed: 
  1. encoding: It specifies the file’s encoding. ‘utf8’ is the default setting. 
  2. mode: The file mode is specified by an integer called mode. ‘0o666’ is the default value. 
  3. flag: It specifies the flag that was used to append the file. ‘a’ is the default value. 
  • callback - This is a function that is performed when the method is invoked. 
  1. err : When a method fails this error is thrown. 

Error Handling

For every developer error handling is important and very essential. It takes a lot of skill to locate and debug a mistake. While working on the above reading and writing files, we noticed an err argument, but we didn’t address it. Let’s have a look at a quick rundown of how to use it: 

While reading or writing a file if there is a runtime error then the callback method is called with an Error object as the first argument. Throwing runtime errors as Node.js exceptions, as we did previously, is the simplest approach to handle them. However, because this can cause the application to crash, it is not recommended unless you have no other choice: 

const fs = require('fs'); 
fs.readFile('404.txt', 'utf-8', (err, data) => { 
if (err) { 
console.error(err); 
// log the error here 
} 
console.log(data); 
}); 

There are two approaches to take when dealing with operational errors, such as specifying an inaccessible path. One option is to pass the error to a callback function. You then include some error-handling logic in the callback, such as logging it. You can also include try/catch blocks around the code that calls the section of the program where errors can occur. 

Conclusion

Like reading files, Node.js has the capability to write files in a precise and sophisticated manner. Reading, writing, and appending files in Node.js are a few of the basic activities that developers must understand when working with Node.JS. 

We have discussed everything about how to read and write a file in Node.Js both in a Synchronous and Asynchronous way. Use the concepts discussed in this blog and create your customized files in Node.js to take your learning journey a step forward. 

If you are planning to learn node.js from scratch, get started with knowledgeHut’s node js program. With easy to understand learning material and hands-on sessions we have all the setup ready to help you upskill and grow. 

Profile

Abhresh Sugandhi

Author

Abhresh is specialized as a corporate trainer, He has a decade of experience in technical training blended with virtual webinars and instructor-led session created courses, tutorials, and articles for organizations. He is also the founder of Nikasio.com, which offers multiple services in technical training, project consulting, content development, etc.

Share This Article
Want to become a sought-after web developer?

Avail your free 1:1 mentorship session.

Select
Your Message (Optional)

Frequently Asked Questions (FAQs)

1How can I create and write to Node.js files?

Ans: For writing a file asynchronously we need to use the fs.writeFile() function. For writing a file synchronously we need to use the function fs.writeFileSync() function.

2How to read a file in Node.js?

Ans: The fs.readFile() is used to read file asynchronously file and fs.readFileSync() is used to read file synchronously.

3How to open a node file?

Ans: To open a NODE file, you'll need software like Node.js. If you're having trouble opening your NODE file, try right-clicking or long-pressing it. After that, select the "Open with" drop-down menu.

4What is the meaning of fs module in Node.js?

Ans: ‘fs’ Module is an inbuilt module provided by Node.js to perform different actions. The ‘fs’ Module is a file system module that helps you to work with files, like read file, write file, append file, and many more

5How do I write to a file synchronously in node?

Ans: We utilise the writeFileSync method in the fs module to write the file in synchronous mode (). The first parameter is the file name, followed by the whole path to the file where the content will be written, and the second parameter is the data that will be written in the file.

Upcoming Web Development Batches & Dates

NameDateFeeKnow more