TIL how to append a date to a filename in Node
POSTED ON:
My goal was to create a helper function that allows me to build a new file, and append a date to a filename for logging.
So:
// BEFORE
filename.js
// AFTER
filename-1644470506946.js
That string of numbers? 1644470506946
is the timestamp in Unix, which you can find the conversion here: https://www.unixtimestamp.com/
But also, it should keep the directory path.
What I came up with: #
function generateFile(src, data, setDate = true) {
const date = Date.now();
// check if there's a slash in it
const directoryOnly = src.substr(0, src.lastIndexOf("/"));
const filenameOnly = src.substring(src.lastIndexOf("/") + 1);
// modify filename with date
let fileName = setDate
? `${filenameOnly.split(".")[0]}-${date}.${filenameOnly.split(".")[1]}`
: filenameOnly;
fs.writeFileSync(`${directoryOnly}/${fileName}`, data, (err) => {
if (err) {
console.error(err);
return;
}
});
}
To use it:
generateFile('./public/data-backup.json', JSON.stringify(result)); // /public/data-backup-1644470506946.json
generateFile('./public/data.json', JSON.stringify(result), false); // /public/data.json
generateFile('./data.json', JSON.stringify(result), true); // data-1644470506946.json
Future improvements #
Consider using path? https://nodejs.org/api/path.html
Related TILs
Tagged: node