how to use the futimessync function from fs-extra in javascript

futimesSync function in fs-extra module of Node.js is used to change the file system timestamp of a particular file synchronously. To use the function, first, we need to install fs-extra module by running the following command in our terminal:

npm install fs-extra

Once installed, we can use it in our code as follows:

index.tsx
const fs = require('fs-extra');
const filePath = './path/to/file.txt';
const now = new Date();
fs.futimesSync(fs.openSync(filePath, 'r+'), now, now);
150 chars
5 lines

Here, we first import the fs-extra module and define the path of our file filePath. Then, we define a new Date object assigned to now, which we will use for the timestamps. After that, we call the futimesSync function with two arguments:

  1. fs.openSync(filePath, 'r+') - This opens the file in read/write mode.
  2. now, now - Timestamps we want to apply to our file. Here, we are passing now as both the access time and modified time.

When this code runs successfully, the file's modified and accessed times will be updated to the current time.

related categories

gistlibby LogSnag