Open In App

Node.js fs.fdatasync() Method

Last Updated : 18 Aug, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The fs module provides an API for interacting with the file-system in a manner closely modeled around standard POSIX functions. All the file system operations have synchronous and asynchronous forms and mostly the asynchronous form takes a completion callback as its last argument.

The fs.fdatasync() (Added in v0.1.96) method is an inbuilt application programming interface of the fs module which is similar to fs.fsync(), it reduces the disk activity for applications that do not require all metadata to be synchronized with the disk. Metadata is needed to allow subsequent data retrieval should be handled correctly as it does not flush modified metadata. 

Syntax:

fs.fdatasync(fd, callback);

The ‘fs‘ module can be accessed using:

const fs = require('fs');

Parameters: This method accepts two parameters as mentioned above and described below:

  • fd <integer>: This parameter accepts <integer> type values.
  • callback <function>: This parameter requires a callback function, and beware of nested callbacks or callback hell.
    • err <Error>: Throws Error, if the callback function is not properly handled. 

Example 1: Filename: index.js

Javascript




// Node.js program to demonstrate the 
// fs.fdatasync() method 
  
// Using require to access fs module 
const fs = require('fs');
  
// Basic demo of fs.fdatasync
fs.fdatasync(1, err => {
    if (err) {
        console.log('error', err);
    }
    else {
        console.log('no-error');
    }
    console.log("Data Sync...");
})
  
// alfa function
function alfa() {
    console.log("Printing callback in "
        + "console from callback alfa... ");
    return "hiii";
}
function data() {
    console.log("Printing callback in "
        + "console from data... ");
}
  
// Open the file
fs.open('filename.txt', "a+", (err, fd) => {
    if (err)
        throw err;
  
    // Write our data
    fs.writeFile(fd, data, (err) => {
  
        // checking error
        if (err)
            throw err;
          
        // Force the file to be flushed
        fs.fdatasync(fd, function alfa(err) {
            if (err)
                throw err
        });
        fs.fdatasync(5, data);
      
        // print after dataSync
        console.log("Writing 'data' in 'filename.txt'... ")
    });
});


Run index.js file using the following command:

node index.js

Output:

error [Error: EBADF: bad file descriptor, fdatasync] {
  errno: -4083,
  code: 'EBADF',
  syscall: 'fdatasync'
}
Data Sync...
Writing 'data' in 'filename.txt'...       
Printing callback in console from data... 

Reference: https://nodejs.org/api/fs.html#fs_fs_fdatasync_fd_callback



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads