The Wayback Machine - https://web.archive.org/web/20240627220502/https://www.geeksforgeeks.org/node-js-fs-open-method/
Open In App

Node fs.open() Method

Last Updated : 15 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

To create the file, to write to a file, or to read a file fs.open() method is used. fs.readFile() is only for reading the file and similarly fs.writeFile() is only for writing to a file, whereas fs.open() method does several operations on a file. First, we need to load the fs class which is a module to access the physical file system. For it require method is used. For example: var fs = require(‘fs’); 

Syntax: 

fs.open( filename, flags, mode, callback )

Parameter: This method accepts four parameters as mentioned above and described below:  

  • filename: It holds the name of the file to read or the entire path if stored at another location.
  • flag: The operation in which the file has to be opened.
  • mode: Sets the mode of the file i.e. r-read, w-write, r+ -readwrite. It sets to default as readwrite.
  • callback: It is a callback function that is called after reading a file. It takes two parameters: 
    • err: If any error occurs.
    • data: A file descriptor, used by subsequent file operations. A file descriptor is a handle used to access a file. It is a non-negative integer uniquely referencing a specific file.

All the types of flags are described below:

Flag Description
r To open the file to read and throws an exception if the file doesn’t exist.
r+ Open the file to read and write. Throws an exception if the file doesn’t exist.
rs+ Open files in synchronous mode to read and write.
w Open file for writing. A file is created if it doesn’t exist.
wx It is the same as ‘w’ but fails if the path exists.
w+ Open the file to read and write. A file is created if it doesn’t exist.
wx+ It is the same as ‘w+’ but fails if the path exists.
a Open the file to append. A file is created if it doesn’t exist.
ax It is the same as a but fails if the path exists.
a+ Open the file for reading and appending. A file is created if it doesn’t exist.
ax+ It is the same as ‘a+’ but fails if the path exists.

Example 1:  Below examples illustrate the fs.open() method in Node.js:

Javascript




// Node.js program to demonstrate the
// fs.open() Method
 
// Include the fs module
const fs = require('fs');
 
// Open file demo.txt in read mode
fs.open('demo.txt', 'r', function (err, f) {
    console.log('Saved!');
});


The file is opened and the flag is set to read mode. After the opening of the file function is called to read the contents of the file and store them in memory. As there are no errors ‘saved‘ is printed.

Output:

Saved! 

Example 2:  Below examples illustrate the fs.open() method in Node.js:

Javascript




// Include the fs module
// Node.js program to demonstrate the
// fs.open() Method
 
// Include the fs module
const fs = require('fs');
 
console.log("Open file!");
 
// To open file in write and read mode,
// create file if doesn't exists.
fs.open('demo.txt', 'w+', function (err, f) {
    if (err) {
        return console.error(err);
    }
    console.log(f);
    console.log("File opened!!");
});


The file ‘demo.txt’ is opened in read and write mode, then the function is called. The output shows a number in the file when we print the value of ‘f’. 

Output: 

Open file!
10
File Opened!

We have a Cheat Sheet on Nodejs fs modules where we covered all the fs methods to check those please go through Node File System Module Complete Reference this article.



Previous Article
Next Article

Similar Reads

Node.js fsPromises.open() Method
The fsPromises.open() method is used to asynchronously open a file that returns a Promise that, when resolved, yields a FileHandle object. Syntax: fsPromises.open( filename, flags, mode) Parameter: This method accepts three parameters as mentioned above and described below: filename: It is a String, Buffer, or URL that holds the name of the file to
2 min read
Node.js Open Weather Map API for Weather Forecasts
The Open Weather Map API is very popular as it allows you to request weather forecasts and historical weather data programmatically.Feature of Open Weather Map API: It is easy to get started and easy to use.It is widely used and popular API for Weather Forecasts. Installation of request module: You can visit the link to Install Request module. You
2 min read
How to Open Node.js Command Prompt ?
Node.js enables the execution of JavaScript code outside a web browser. It is not a framework or a programming language, but rather a backend JavaScript runtime environment that allows scripts to be executed outside the browser. You can download Node.js from the web by visiting the link "Download Node" and downloading the latest version onto your m
2 min read
Javascript Window Open() & Window Close() Method
The Javascript Window.Open() method is used to open the web pages into a new window or a new tab. It depends on the browser settings and the values that are assigned to the parameter. Syntax: window.open(URL, name, specs, replace) Parameters: This method accepts four parameters as mentioned above and described below: URL: It is an optional paramete
3 min read
HTML DOM open() Method
The DOM Open() method in HTML is the combination of the following three steps: Opens an output stream to collect the output.Collects output from the document.write() or document.writeln() methods.Runs the document.close to display the output written to the output stream. Syntax: document.open( MIMEtype, replace ) Parameter Values: This method accep
2 min read
HTML DOM indexedDB open() Method
The open() method of the indexedDB interface requests opening a connection to a database. This method returns an IDBOpenDBRequest object immediately and performs the open operation asynchronously. Syntax: var IDBOpenDBRequest = indexedDB.open(name); // Or var IDBOpenDBRequest = indexedDB.open(name, version); Parameters: This method accepts two para
2 min read
jQuery UI dialog open() Method
open() Method is used to open the dialog. This method does not accept any argument Syntax: $( ".selector" ).dialog("open"); Approach: First, add jQuery UI scripts needed for your project. <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10
1 min read
jQuery UI Tooltips open() Method
jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery, CSS, and HTML. jQuery UI is great for building UI interfaces for the webpages. jQuery UI tooltip widget helps us to adds new themes and allows for customization. In this article, we will see how to use open option in jQuery UI tooltips. The open option is used t
1 min read
jQWidgets jqxComboBox open() Method
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxComboBox is used to represent a jQuery Combobox widget that contains an input field with autocomplete functionality and a list of selectable items displayed i
2 min read
jQWidgets jqxTooltip open() Method
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful and optimized framework, platform-independent, and widely supported framework. The jqxTooltip is a jQuery widget that is used to display a popup message. The jqxTooltip widget can be used in combination with any HTML element. The o
2 min read
three90RightbarBannerImg