- How to read and write files in Node.js
- You might also like.
- JavaScript Read and Write to Text File
- JavaScript Read and Write to Text File
- Method 1: Using Node.js
- Method 2: Using ActiveXObject
- How to read and write a file using Javascript?
- Write operation on a file
- Example 1
- Reading from the file
- Syntax
- Example 2
- Output
- Example 3
How to read and write files in Node.js
You can use the fs module to read and write files in Node.js. The fs module is a built-in module in Node.js that provides both asynchronous and synchronous functions to read, write, and watch files.
The simplest way to read a file in Node.js is to use the fs.readFile() method by passing the file path, encoding, and a callback function. It asynchronously reads the entire contents of the file and calls the callback function with the file data:
const fs = require('fs') fs.readFile('file.txt', 'utf-8', (err, data) => if (err) throw err > console.log(data) >)
const fs = require('fs') try const data = fs.readFileSync('file.txt', 'utf-8') console.log(data) > catch (err) console.error(err) >
Note: If you skip the encoding parameter, a raw buffer is returned. Otherwise, a string is returned.
const fsPromises = require('fs/promises') const readFileAsync = async () => try const data = await fsPromises.readFile('file.txt', 'utf-8') console.log(data) > catch (err) console.error(err) > > readFileAsync()
All the above three functions read the complete file contents in memory before calling the callback function and returning data. This means that if you are reading a large file, it might have an impact on your memory consumption and execution of the program. For large files, it is better to use streams for reading the contents of a file.
The easiest way to write data to files in Node.js is using the fs.writeFile() method. This method takes three parameters: the file path, the data to write, and a callback function, and writes the data asynchronously:
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('File is written successfully.') >)
const fs = require('fs') const data = 'This is the new content of the file.' try fs.writeFileSync('file.txt', data) console.log('File is written successfully.') > catch (error) console.error(err) >
const fsPromises = require('fs/promises') const writeFileAsync = async () => try const data = 'This is the new content of the file.' await fsPromises.writeFile('file.txt', data) console.log('File is written successfully.') > catch (err) console.error(err) > > writeFileAsync()
By default, the above methods override the file contents if it already exists. To append data to the file, you should pass a flag as the 3rd parameter:
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.') >)
- r — Open the file in read-only mode. An exception is thrown if the file does not exist.
- r+ — Open the file for reading and writing. If the file does not exist, an exception is thrown.
- w — Open the file in write-only mode. The file is created (only if does not already exist) or truncated (if exists).
- w+ — Open the file for reading and writing, placing the stream at the start of the file. The file is created if doesn’t exist.
- a — Open the file for appending, positioning the stream at the end of the file. The file is created if doesn’t exist.
- a+ — Open the file for reading and appending, putting the stream at the end of the file. The file is created if it does not exist.
All the above methods continue writing to the file until the complete contents have been written before returning the control back to your program.
If you are writing a lot of data, it might impact your application performance. In this case, a better approach would be to use a stream for writing to large files.
Apart from flags, the fs module also provides fs.appendFile() (and fs.appendFileSync() for synchronous) method that asynchronously append data to the file, creating the file if it does not yet exist:
const fs = require('fs') const data = 'Some data to append' fs.appendFile('file.txt', data, err => if (err) throw err > console.log('File is updated.') >)
If there is a runtime error while reading or writing to a file, the callback method is called with an Error object as the first argument. The simplest way to handle runtime errors is to throw them as Node.js exceptions like above. But this will crash the application and is therefore not recommended except in cases where 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) >)
[Error: ENOENT: no such file or directory, open '404.txt'] errno: -2, code: 'ENOENT', syscall: 'open', path: '404.txt' > undefined
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
You might also like.
JavaScript Read and Write to Text File
In this tutorial, I will tell you about how you can read and write to text file using JavaScript. As we know JavaScript does not have the ability to access the user’s file system so for this we need to run the project on a server. To implement this we use node.js.
In node.js these are one library fs (File-System) which is used to manage all read and write operations. By using the fs module we can read and write files in both synchronous and asynchronous way.
There are many ways in which we can read and write data to file. Lets have a look on each of them one by one.
JavaScript Read and Write to Text File
Method 1: Using Node.js
First is by using writefile and readFile method in node.js environment.
This is used to write content to file. Its syntax is below:
It has three parameters path, data, callback.
Path: The path is the location of Text File. If the file is to be generated in the same folder as that of the program, then provide the name of the file only. If the file does not exist then the new file will be created automatically.
Data: Second is Data in This parameter we need to pass info that is required to write in the file.
Callback: Last one is the Callback Function in this we pass error string. If the operation fails to write the data, an error shows the fault.
To run above code run this command:
>node index.js
It is used to read the content of the file. its syntax is:
It also has three parameters path, callback, options.
path is a location of Text File. If both file and program are in a similar folder, then directly give the file name of the text file.
Second option which specifies the data is to be gathered from the file and it is optional. If you pass nothing then it returns raw buffer.
The last one is Callback function which has two more parameters (error, txtString). If at any instance it fails to load or read the file then it returns error or exception otherwise it returns all data of the file.
To run this program enter below command:
>node index.js
Method 2: Using ActiveXObject
Another method is by using a web page ActiveX objects but this method is mainly work in Internet Explorer only.
This ActiveXObject is used to return an instance of a file system library which is used with the CreateTextFile method. This JS method which generates a file defined functions and states a TextStream object to read from or write to the file. It also returns a boolean value on the basis of this we can find out that we can overwrite to the current file or not. So, if you want to add the data to the created file you can use writeline method which is used to add text string to the file.
Using ActiveX objects, the following should be included in your code to read a file:
The ActiveX object contains three things libraryname, classname, location. So, classname is the instance of a class that needs to be created. libraryname is a mandatory field and it is the sign of the app giving the object.
To open a new file:
How to read and write a file using Javascript?
The read and write operations in a file can be done by using some commands. But the module which is required to perform these operations is to be imported. The required module is ‘fs’ which is called as File System module in JavaScript.
Write operation on a file
After the File System file is imported then, the writeFile() operation is called. The writeFile() method is used to write into the file in JavaScript. The syntax of this method is as follows −
writeFile(path,inputData,callBackFunction)
The writeFile() function accepts three parameters −
- Path − The first parameter is the path of the file or the name of the file into which the input data is to be written. If there is a file already, then the contents in the file are deleted and the input which is given by the user will get updated or if the file is not present, then the file with that will be created in the given path and the input information is written into it.
- inputData − The second parameter is the input data which contains the data to be written in the file that is opened.
- callBackFuntion − The third parameter is the function which is the call back function which takes the error as the parameter and shows the fault if the write operation fails.
Example 1
Following is an example of the write operation in files in JavaScript.
const fs = require('fs') let fInput = "You are reading the content from Tutorials Point" fs.writeFile('tp.txt', fInput, (err) => if (err) throw err; else console.log("The file is updated with the given data") > >)
If you open input file you can observe the written data in it as shown below −
Reading from the file
After the File System module is imported, the reading of the file in JavaScript can be done by using the readFile() function.
Syntax
The syntax to read from a file is as follows −
readFile(path, format, callBackFunc)
The readFile() function accepts three parameters including one optional parameter.
- Path − The first parameter is the path of the test file from which the contents are to read. If the current location or directory is the same directory where the file which is to be opened and read is located then, only the file name has to be given.
- Format − The second parameter is the optional parameter which is the format of the text file. The format can be ASCII, utf-8 etc.
- CallBackFunc − The third parameter is the call back function which takes the error as the parameter and displays the fault is any raised due to the error.
Example 2
Following example tries to read the contents of the file populate in the previous example and print it −
const fs = require('fs') fs.readFile('tp.txt', (err, inputD) => if (err) throw err; console.log(inputD.toString()); >)
Output
Following is the output of the above example −
You are reading the content from Tutorials Point
The text which is displayed in the console is the text which is in the given file.
Example 3
Following is a combined example of the above of reading and writing files using the fs module on node.js. Let us create a JS file named main.js having the following code −
var fs = require("fs"); console.log("Going to write into existing file"); // Open a new file with name input.txt and write Simply Easy Learning! to it. fs.writeFile('input.txt', 'Simply Easy Learning!', function(err) console.log("Data written successfully!"); console.log("Let's read newly written data"); // Read the newly written file and print all of its content on the console fs.readFile('input.txt', function (err, data) console.log("Asynchronous read: " + data.toString()); >); >);