0

I am using facebook authentication and want to save user avatar from url to a folder on the server. The user avatar is stored in my variable ${picture}

  await mkdir(`${dir}/dist/users/${insertId}`)
  if (!facebookLogin) {
    fs.createReadStream(`${dir}/dist/images/users.jpg`).pipe(
      fs.createWriteStream(`${dir}/dist/users/${insertId}/avatar.jpg`)
    )
  }
  else {
    fs.createReadStream(`${picture}`).pipe(
      fs.createWriteStream(`${dir}/dist/users/${insertId}/avatar.jpg`)
    )
  }

The part that is NOT working is in the ELSE LOOP (facebook login user) fs.createReadStream('${picture}') as this tries to fecth it from C:\xampp\htdocs\https:\platform-lookaside.fbsbx.com\platform\profilepic\?..........

I want it to directly copy from https:\platform-lookaside.fbsbx.com\platform\profilepic\?.............

May be I should not use fs.createReadStream as the image is in a url now. How can I change this to copy image fro url to server?

1 Answer 1

2

What if you use request module? (https://github.com/request/request)

As the response from request is a stream too, you can use the same method from fs to write the image on the server.

Then, I guess that it will works:

With request lib: request(picture).pipe(fs.createWriteStream(${dir}/dist/users/${insertId}/avatar.jpg))

With native http module from node (https://nodejs.org/api/http.html):

var http = require('http');
var fs = require('fs');

var request = http.get(picture, function(res){
    var imageData = '';
    res.setEncoding('binary');

    res.on('data', function(chunk){
        imagedata += chunk;
    });

    res.on('end', function(){
        fs.writeFile(`${dir}/dist/users/${insertId}/avatar.jpg`, imagedata, 'binary', function(err){
            if (err) throw err;
            //Here the file was saved
        })
    })

})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.