K
K
Konstantin Chuykov2015-06-05 01:25:06
Node.js
Konstantin Chuykov, 2015-06-05 01:25:06

How to make a static store with NodeJS?

Hello! Using passport.js, I authorize users, I want to save their avatar to my server. I created the directories /static/avatar/, assigned write permissions, and wrote a simple script for generating the path to the image:

var avatar = function(email, id, url) 
    {
        var hash = crypto.createHash('md5')
            .update(email)
            .update(id)
            .digest('hex');
        
        var uri = hash.substr(29,3) + '/' + hash.substr(26,3) + '/' + hash.substr(0,26) + '/' + hash + '.jpg';
        
        var file = fs.createWriteStream(path.join(__dirname, '../static/avatar/' + uri));

        https.get(url, function(res) {
            console.log("statusCode: ", res.statusCode);
            console.log("headers: ", res.headers);
            res.on('data', function(d) {
                file.write(d);
            });
        }).on('error', function(e) {
            console.error(e);
        });
        
        return uri;
    }

But I get the error Error: ENOENT, open __dirname ' /static/avatar/041/f90/bd29c83187f7965108cdaa2574/bd29c83187f7965108cdaa2574f90041.jpg'.
I understand that the problem is due to the fact that there are no directories, do you really need to add more lines that create directories, or is there a simpler option?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Timur Shemsedinov, 2015-06-05
@chuikoffru

// И для этого есть https://www.npmjs.com/package/mkdirp
var mkdirp = require('mkdirp');
    
mkdirp('/tmp/foo/bar/baz', function (err) {
    if (err) console.error(err)
    else console.log('pow!')
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question