S'rCat
S'rCat

Reputation: 638

In Nodejs does "stat'ing" a file change the access time?

In Nodejs on a mac I'm trying to get the last access time of a file using fs.statSync(). The access time is always the time the fs.statSync was executed. Makes sense, but not what I want.

How do I get the last time a file was accessed aside from the fs.stat?

Upvotes: 2

Views: 592

Answers (2)

S'rCat
S'rCat

Reputation: 638

Here's more info: This is a test.js.

const fs = require('fs');
const recoverFile = "recoverFile.json";

var stat = fs.statSync(recoverFile);
let now = Date.now();
const timeDelta = now - Math.round(stat.atimeMs);

console.log("time delta: "+timeDelta);

let data = fs.readFileSync( recoverFile );
stat = fs.statSync(recoverFile); // COMMENT ME OUT

This will print the correct time between evocations. Now, comment out the last line and run it again. On my MacBook, it shows 0 ms between evocations.

Upvotes: 0

Dmitry Minkovsky
Dmitry Minkovsky

Reputation: 38143

does “stat'ing” a file change the access time?

I don't think so. I just tried this on my computer (macOS 10.15, Node 15):

$ stat useName.ts 
16777220 157432179 -rw-r--r-- 1 dmitry staff 0 856 "Nov 13 16:27:23 2020" "Oct 29 22:39:08 2020" "Oct 29 22:39:08 2020" "Jun 28 08:31:51 2020" 4096 8 0 useName.ts
> fs.statSync('useName.ts')
Stats {
  dev: 16777220,
  mode: 33188,
  nlink: 1,
  uid: 501,
  gid: 20,
  rdev: 0,
  blksize: 4096,
  ino: 157432179,
  size: 856,
  blocks: 8,
  atimeMs: 1605302843377.5464,
  mtimeMs: 1604025548575.2034,
  ctimeMs: 1604025548575.2034,
  birthtimeMs: 1593347511907.6377,
  atime: 2020-11-13T21:27:23.378Z,
  mtime: 2020-10-30T02:39:08.575Z,
  ctime: 2020-10-30T02:39:08.575Z,
  birthtime: 2020-06-28T12:31:51.908Z
}

Repeatedly issuing either command yields the same results.

Upvotes: 1

Related Questions