2
\$\begingroup\$

My code below creates a folder based on the passed data from my client-side(VueJs) and checks if there's already an existing folder and deletes it if there is otherwise it will create a new one.

My problem here is that I think my code is too long and unreadable although it accomplishes the task that I want to happen.

Can someone help me to make this code better?

router.post('/album', (req, res) => {
    let sql = "INSERT INTO GALLERY SET ALBUM = ?, DESCRIPTION = ?";
    let body = [req.body.ALBUM, req.body.DESCRIPTION]
    myDB.query(sql, body, (error, results) => {
        if (error) {
            console.log(error);
        } else {
            let directory = `path\\public\\${req.body.ALBUM}`;
            if (fse.existsSync(directory)) {
                fse.removeSync(directory, err => {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log("Success");
                    }
                })
            } else {
                fse.mkdirpSync(directory, err => {
                    if (err) {
                        console.log(object);
                    } else {
                        console.log("Success");
                    }
                })
            }
        }
    })
})
\$\endgroup\$
  • \$\begingroup\$ Could you add what the req object contains in detail? And explain where fse is coming from, I'm guessing it's a file system access, but more detail wouldn't hurt. \$\endgroup\$ – IEatBagels Nov 26 '19 at 1:55
  • \$\begingroup\$ What is the benefit from removing the whole directory every time? \$\endgroup\$ – RomanPerekhrest Nov 26 '19 at 7:13
2
\$\begingroup\$

The built in file system package (fs) provides you with a commands to create directories.

fs.mkdirSync(path[, options]) for synchronous

fs.mkdir(path[, options], callback) for asynchronous

According to their documentation, you can add an option for recursively creating a folder. It also notes

"Calling fs.mkdir() when path is a directory that exists results in an error only when recursive is false."

With this information, you should be able to force it to always create the folder using only this logic:

const fs = require('fs')
fs.mkdir( directory, { recursive: true }, (err) => {
  if (err) throw err;
});
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.