1

I want to set the last modified date of a file to the current date in order to avoid Parcel caching (unfortunately I didn't find a better way).

So I wrote that:

const fs = require('fs');
const file = 'test.txt';

// save the content of the file
const content = fs.readFileSync(file);

// modify the file
fs.appendFileSync(file, ' ');

// restore the file content
fs.writeFileSync(file, content);

It works but meh...
It's really ugly and it's very slow and memory consuming for big files.

Cl00e9ment
  • 773
  • 1
  • 13
  • 30

1 Answers1

4

Adapted from https://remarkablemark.org/blog/2017/12/17/touch-file-nodejs/:

const fs = require('fs');
const filename = 'test.txt';
const time = new Date();

try {
  fs.utimesSync(filename, time, time);
} catch (err) {
  fs.closeSync(fs.openSync(filename, 'w'));
}

fs.utimesSync is used here to prevent existing file contents from being overwritten.

It also updates the last modification timestamp of the file, which is consistent with what POSIX touch does.

sonofagun
  • 355
  • 2
  • 7