Ulysses
Ulysses

Reputation: 6015

javascript: Creating directories from file path recursively adding timestamp to the filename

I am using the below code to split up a user provided path, create all intermediate dirs in the path and attach a timestamp to the ending file name. I am splitting the path with / first and then using forEach over the resulting array. Is there any better way/direct lib function to do this in javascript / nodejs.

function test(usrPath) {
    var locMatches = usrPath.split("/")     
    locMatches.forEach (function (item) {
        location = pathUtils.join(location,item)
        if (!fs.existsSync(location)) {
            fs.mkdirSync(location)
        }
    })      
    return pathUtils.join (location,usrPath + (new Date).toISOString().replace(/(^\d\d\d\d)|-|:|(\..*)/g,"").replace("T","_")+".log")
}

Upvotes: 1

Views: 185

Answers (1)

Ulysses
Ulysses

Reputation: 6015

Ok, so there are path utils that allow to make the implementation better across platform.

Also, it gives a better managed access for working with path elements like root, dir, filename and extension. pathUtils.sep allows working on the dir elements more cross platform.

var pathUtils = require('path')
function test(usrPath) {
    var pathElements = pathUtils.parse(usrPath)
    pathElements.dir.split(pathUtils.sep).forEach (function (item) {
        location = pathUtils.join(location,item)
        if (!fs.existsSync(location)) {
            fs.mkdirSync(location)
        }
    })      
    return pathUtils.join (location,pathElements.name + (new Date).toISOString().replace(/(^\d\d\d\d)|-|:|(\..*)/g,"").replace("T","_")+pathElements.ext.replace(/^$/i,".log"))
}

Upvotes: 1

Related Questions