-2

I would like to save an image (link obtained) with just plain nodejs (no additional 'require' beside those natively packaged with node). Let say I have image with link: https://i.stack.imgur.com/9JkxM.jpg

needing this image to be save into folder ./picsFolder

Thanks a bunch.

Andy
  • 1
  • 2
  • Why dont you read existing libraries? But basically its get the stream and write it. – Estradiaz Apr 17 '20 at 06:33
  • Use `http.request()` - https://nodejs.org/api/http.html#http_http_request_options_callback – slebetman Apr 17 '20 at 06:33
  • You can also check out this thread. There are answers that use vanilla node: https://stackoverflow.com/questions/12740659/downloading-images-with-node-js – Mike Apr 17 '20 at 06:36
  • @Estradiaz Is there a more approachable way to understand nodejs docs for beginner, like an example? – Andy Apr 17 '20 at 06:47

2 Answers2

1

You can tweak this snippet.

An HTTP request is an (input) stream of data that you can direct to another (output) stream.

To go deeper with streams read here

const https = require('https')
const fs = require('fs')
const options = {
  hostname: 'i.imgur.com',
  port: 443,
  path: '/UiiCTfN.jpg',
  method: 'GET'
}

const req = https.request(options, res => {
  console.log(`statusCode: ${res.statusCode}`)

  const imgStream = fs.createWriteStream('./myimg.jpg')

  res.pipe(imgStream)
})

req.on('error', error => {
  console.error(error)
})

req.end()
Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73
  • Thanks Manuel Spigolon, this work too. Is the port value arbitrary? – Andy Apr 17 '20 at 07:16
  • No, it should be 443 for https and 80 for HTTP, it depends on the protocol and by the endpoint, you are calling. if it is a custom API it could be 3000 as well – Manuel Spigolon Apr 17 '20 at 07:27
0

ref thread: Downloading images with node.js by Nihey Takizawa

var http = require('https'),                                                
    Stream = require('stream').Transform,                                  
    fs = require('fs');                                                    

var url = 'https://i.imgur.com/UiiCTfN.jpg';                    

http.request(url, function(response) {                                        
  var data = new Stream();                                                    

  response.on('data', function(chunk) {                                       
    data.push(chunk);                                                         
  });                                                                         

  response.on('end', function() {                                             
    fs.writeFileSync('./picsFolder/yourImgName.png', data.read());                               
  });                                                                         
}).end();
Andy
  • 1
  • 2