javascriptnode.jsbackendnode.js-fs

create file on folder if not exists on node js


I want to creat directory if not exist and then save the file that I got from Front-end

This is my code and it only does the part of creating folders, but my main problem is saving the file in this path

let directory = await './some-dir/'+d.getFullYear()+'/'+("0" + (d.getMonth() + 1)).slice(-2)+'/'+(d.getDay().toString().padStart(2, "0"))+'/'+d.getHours()+'/'+d.getMinutes()+'/'+d.getSeconds()
    fs.mkdirSync(directory, { recursive: true })

Solution

  • If we want to create a file in a folder (both of them do not exist), we can use this way. Of course, in this example, the path of the file (folders) is first the number of the current year, then the number of the current month, and finally the current day For the file name, the time of file creation is considered as the name The value inside the file is also sent by the front-end request.body.values[0]

    import fs from 'fs';
    import path from 'path';
    
    let d= new Date()
            const directory = await './some-dir/'+d.getFullYear()+'/'+("0" + (d.getMonth() + 1)).slice(-2)+'/'+(d.getDay().toString().padStart(2, "0"))
            let name= (d.getHours() + '-' + d.getMinutes() + '-' + d.getSeconds()).toString()+".txt"
            fs.mkdirSync(directory, { recursive: true })
            fs.writeFileSync(path.join(directory,name), request.body.values[0],"UTF8")