文件名 JS 中的时间戳

use*_*478 7 javascript timestamp

我想在 XML 文件从位置 A 复制到 B 时为其添加时间戳。

const fs = require('fs');

// destination.txt will be created or overwritten by default.
fs.copyFile('\\\\IP\\FOLDER\\FILE.xml', 'c:\\FOLDER\\FILE.xml', (err) => {
  if (err) throw err;
  console.log('OK! Copy FILE.xml');
});
Run Code Online (Sandbox Code Playgroud)

副本有效,但我不知道如何添加时间戳。

Pat*_*und 9

Date.now为您提供时间戳(即自 1970 年 1 月 1 日以来经过的毫秒数)。

您可以将其添加到 的第二个参数中copyFile,即文件名的目标路径。

例子:

const fs = require('fs');

// destination.txt will be created or overwritten by default.
fs.copyFile('\\\\IP\\FOLDER\\FILE.xml', `c:\\FOLDER\\FILE_${Date.now()}.xml`, (err) => {
  if (err) throw err;
  console.log('OK! Copy FILE.xml');
});
Run Code Online (Sandbox Code Playgroud)

注意后面的勾号——这是一个 JavaScript 模板字符串,允许您使用${}.

如果您需要当前日期的日期字符串,正如您在评论中指出的,您可以编写一个小辅助函数来创建此字符串:

const fs = require('fs');

function getDateString() {
  const date = new Date();
  const year = date.getFullYear();
  const month = `${date.getMonth() + 1}`.padStart(2, '0');
  const day =`${date.getDate()}`.padStart(2, '0');
  return `${year}${month}${day}`
}

// destination.txt will be created or overwritten by default.
fs.copyFile('\\\\IP\\FOLDER\\FILE.xml', `c:\\FOLDER\\FILE_${getDateString()}.xml`, (err) => {
  if (err) throw err;
  console.log('OK! Copy FILE.xml');
});
Run Code Online (Sandbox Code Playgroud)

这将创建一个这样的文件名:FILE_20182809.xml