Today I Learned - Rocky Kev

TIL how to append a date to a filename in Node

POSTED ON:

TAGS:

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:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL keywords in package.json

Today I learned what keywords are in a package.json file! It's a collection of keywords about a module. Keywords can help identify a package, related modules and software, and concepts.

TIL functional async/await

PLACEHOLDER