获取节点中的文件创建日期

Get file created date in node

本文关键字:文件 创建日期 节点 获取      更新时间:2023-09-26

在节点中,我可以使用标准的file stat对象来获取文件的修改日期。有没有一种方法我也可以找到它的创建日期?我在里面找不到任何东西http://nodejs.org/api/fs.html#fs_class_fs_stats文件。

如果有人在这么长时间后偶然发现了这一点,从Node v0.12.0开始,使用这个:

fs.stat(path, callback)

其中回调有两个参数err&统计数据。Stats对象具有属性

birthtime

即创建日期。

链接到节点api文档链接

是否可以获得文件创建时间取决于操作系统和文件系统。传统的POSIX只定义ctime,它是(相当令人困惑的)inode修改日期,而不是其他人提到的创建日期。但是,在某些操作系统上,您可以获得st_birthtimespec或st_birchtime,这是一个真正的"创建"时间。您需要检查主机操作系统上的sys/stat.h,看看有什么可用的。

不幸的是,是否可以从node.js访问整个stat结构是另一回事。但至少你可以弄清楚你的操作系统是否支持它,然后从那里开始。

2019年更新:

您可以随时访问此属性,但在许多文件系统中,这是错误的。根据Node.js文档:

在出生时间不可用的文件系统上,此字段可能包含ctime或1970-01-01T00:00Z(即Unix epoch时间戳0)。在这种情况下,该值可能大于atime或mtime。在Darwin和其他FreeBSD变体上,如果使用utimes(2)系统调用将atime显式设置为比当前出生时间更早的值,也要设置。https://nodejs.org/api/fs.html#fs_stats_birthtimems

如果您使用的是Linux,那么这些信息是不可访问的(尽管它存储在Ext4文件系统中)。因此,fs.stat仅返回atimectimemtime值。

这是一个在Linux和macOS上都很适用的解决方案(对不起Windows用户)。

它是一个可以导入到其他代码中的模块,该模块使用Node的util.exec()方法作为子进程传递UNIX命令,并返回转换为整数的UNIX时间戳字符串。

如果子进程失败,它将返回null

const util = require("util");
const exec = util.promisify(require("child_process").exec);
const executeCommand = async (cmd) => {
  try {
    return await exec(cmd, { timeout: 2000 }).then(async ({ stdout, stderr }) => {
      if (stderr) {
        return null;
      }
      if (stdout) {
        return stdout;
      }
    });
  } catch (cmdErr) {
    return null;
  }
};
exports.getFileDate = async (filePath) => {
  try {
    let cmd = ``;
    if (process.platform === "linux") {
      cmd = `stat -c %Y "${filePath}"`;
    } else if (process.platform === "darwin") {
      cmd = `stat -s "${filePath}"`;
    } else {
      console.error(`getFileDate() => Error: only 'linux' and 'darwin' platforms are supported`);
      return null;
    }
    let getDateResult = await executeCommand(cmd);
    if (getDateResult === null) {
      return null;
    }
    // Linux
    if (process.platform === "linux") {
      getDateResult = parseInt(getDateResult);
      return getDateResult;
    }
    // macOS
    else if (process.platform === "darwin") {
      // get the index where creation time starts
      let start = getDateResult.indexOf("st_ctime");
      // different timestamps are delimited by spaces
      let creationDate = getDateResult.substring(start, getDateResult.length);
      // parse the complete string to get 'st_ctime' value
      let splitResult = creationDate.split(" ");
      let timestamp = splitResult[0].replace("st_ctime=", "");
      // return 'null' if it's not a number
      if (isNaN(timestamp)) {
        return null;
      } else {
        timestamp = parseInt(timestamp);
        return timestamp;
      }
    }
    // catch errors
  } catch (err) {
    console.error(`getFileDate() => ${err}`);
    return null;
  }
};

只需将这个新模块导入另一个脚本中即可(假设它在同一目录中):

const { getFileDate } = require("./getFileDate");

然后可以将文件路径传递给函数调用,并将UNIX时间戳转换为可读的日期字符串,如下所示:

let unixTimestamp = await getFileDate("path/to/some/file.txt");
let dateStr = new Date(unixTimestamp * 1000);
console.log(dateStr);

我使用的是Fedora,在fs.stat结果中没有"birthtime"字段。但也许您可以尝试使用node的child_process来调用ls——fully。至少在我的机器上,它给了我正确的结果。

fs.stat结果:

{ dev: 64771,
  mode: 33279,
  nlink: 1,
  uid: 1000,
  gid: 1000,
  rdev: 0,
  blksize: 4096,
  ino: 2098445,
  size: 48523700,
  blocks: 94776,
  atime: Sat Jul 04 2015 19:01:29 GMT+1000 (AEST),
  mtime: Thu Aug 22 2013 16:45:10 GMT+1000 (AEST),
  ctime: Sat Jul 04 2015 19:01:29 GMT+1000 (AEST) }

ls—全职

  -rwxrwxrwx. 1 pahuang pahuang 22M 2013-06-23 17:51:08.000000000 +1000 test_media/processed/20130621.mkv