Kal
Kal

Reputation: 1774

NodeJs / React App - save or copy image from url to server

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?

Upvotes: 0

Views: 228

Answers (1)

Ramon Sena
Ramon Sena

Reputation: 71

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
        })
    })

})

Upvotes: 2

Related Questions