gpt4 book ai didi

javascript - 文件名 JS 中的时间戳

转载 作者:行者123 更新时间:2023-11-30 14:22:18 26 4
gpt4 key购买 nike

我想在 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');
});

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

最佳答案

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');
});

注意反引号 - 这是一个 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');
});

这将创建如下文件名:FILE_20182809.xml

关于javascript - 文件名 JS 中的时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52553774/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com