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.

4
  • You can use touch -m test.txt Commented Jan 26, 2020 at 18:23
  • @yuko touch isn't cross-platform. I search something that will work everytime so a native Node.js function or a good NPM module. Commented Jan 26, 2020 at 18:30
  • 1
    Maybe you'll find fs.utimes useful Commented Jan 26, 2020 at 18:40
  • @yuko I've just tested it and it works thanks. Commented Jan 26, 2020 at 18:50

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.