![]() |
VOOZH | about |
Node.js is used for server-side scripting. Reading and writing files are the two most important operations that are performed in any application. Node.js offers a wide range of inbuilt functionalities to perform read and write operations. The fs package contains the functions required for file operations. The read() method of the fs package reads the file using a file descriptor. In order to read files without file descriptors the readFile() method of the fs package can be used.
Syntax
fs.read(fd, buffer, offset, length, position, callback)Parameters:
err: An Error object is provided if an error occurs during the read operation. Otherwise, it is null.bytesRead: The number of bytes read from the file.buffer: The buffer object passed to the method, filled with the data read from the file.The fs.open() method opens the file and returns a file descriptor. A file descriptor is a number or index that is stored in the file descriptor table by the kernel and is used to uniquely identify an open file in the computer's operating system. The fs.read() method reads the file using the file descriptor and stores it in the buffer. The contents of the buffer are printed out as output. The fs.close() method is used to close the file.
Example 1: In this example, we will use fs.read() method
Output:
Open existing file
Reading the file
0 bytes read
File closed successfullyExample 2: Taking dynamic input for file name/path.
Output:
C:\Users\User\Desktop>node read3.js
Enter file path: new.txt
Entered path : new.txt
File Content
Hello World..
Welcome to GeeksForGeeks..
This is a Node.js program