最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Timestamp in file name JS - Stack Overflow

programmeradmin0浏览0评论

I want to add a time stamp to a XML file while it's copy from location A to 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');
});

The copy works, but I have no idea how to add the time stamp.

I want to add a time stamp to a XML file while it's copy from location A to 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');
});

The copy works, but I have no idea how to add the time stamp.

Share Improve this question asked Sep 28, 2018 at 10:51 user3130478user3130478 2171 gold badge4 silver badges12 bronze badges 1
  • what do you mean "add a timestamp". Add it where? On the filename? Inside the file? Something else? Please be clear about your requirement. P.S. Is this NodeJS? Please tag it appropriately if so. – ADyson Commented Sep 28, 2018 at 11:02
Add a comment  | 

1 Answer 1

Reset to default 15

Date.now gives you a time stamp (i.e. the number elapsed of milliseconds since 1 Jan 1970).

You can add it to the second argument for copyFile, which is the destination path an file name.

Example:

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

Note the back ticks – that's a JavaScript template string that allows you to add data using ${}.

If you need a date string of the current day, as you pointed out in the comments, you can write a little helper function that creates this string:

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

This will create a file name like this: FILE_20182809.xml

发布评论

评论列表(0)

  1. 暂无评论