File upload: create a directory if it does not exist

I handle file uploads in NodeJS with the formidable. This works for me. Now I want to structure the downloads a little more. I am passing a field from angular with my downloads, which is project_id. I want to create a folder in my downloads called this identifier and write files to it.

So, I check if the directory exists, if I do not create it with fs.mkdir, and then write the files to it. Trying this, I get an error EINVAL, renameand an HTTP 500 status code.

This is my attempt, did anyone understand how to fix this?

 app.post('/uploads/', function(req, res, next){
        var form = new formidable.IncomingForm();
        form.keepExtensions = true;
        form.parse(req, function(err, fields, files){
            if (err) next (err);
            fs.exists('uploads/' + fields.project_id + '/', function (exists){
                if (exists) {
                    fs.rename(files.upload.path, 'uploads/' + fields.project_id + '/' +files.upload.name, function(err){
                        if (err) next (err);
                        res.render('profile.ejs',{
                            user: req.user
                        });
                    });
                } else {
                    fs.mkdir('uploads/' + fields.project_id + '/', function (err){
                        if (err) next (err);
                    });
                    fs.rename(files.upload.path, 'uploads/' + fields.project_id + '/' + files.upload.name, function(err){
                        if(err) next (err);
                        res.render('profile.ejs',{
                            user:req.user
                        });
                    });
                }
            });
        });
    });
+4
source share
1 answer

. , fs.exists , .

, path . , , . , EEXIST.

:

// add this to the beggining
var path = require('path');

app.post('/uploads', function(req, res, next){
    var form = new formidable.IncomingForm();
    form.keepExtensions = true;
    form.parse(req, function(err, fields, files){
        if (err) next (err);
        fs.mkdir(path.resolve('uploads', fields.project_id), function (err) {
            if (err && err !== 'EEXIST') {
                next(err);
            } else {
                fs.rename(files.upload.path, path.resolve('uploads', fields.project_id, files.upload.name), function(err){
                    if(err) next (err);
                    res.render('profile.ejs',{
                        user:req.user
                    });
                });
            }
        });
    });
});
+3

All Articles