Categories
JavaScript Answers

How to write an image to a local server with Node.js?

Spread the love

Sometimes, we want to write an image to a local server with Node.js.

In this article, we’ll look at how to write an image to a local server with Node.js.

How to write an image to a local server with Node.js?

To write an image to a local server with Node.js, we can use the fs.writeFile method.

For instance, we write

const http = require('http')
const fs = require('fs')

const options = {
  host: 'www.google.com',
  port: 80,
  path: '/images/logos/ps_logo2.png'
}

const request = http.get(options, (res) => {
  let imageData = ''
  res.setEncoding('binary')

  res.on('data', (chunk) => {
    imageData += chunk
  })

  res.on('end', () => {
    fs.writeFile('logo.png', imageData, 'binary', (err) => {
      if (err) {
        throw err
      }
      console.log('File saved.')
    })
  })
})

to call res.on with 'data' to listen for image data from the request we made with http.get.

We concatenate the chunks to imageData to combine the response data retrieved from the res stream.

And then we call res.on with 'end' to listen for the end event.

In the callback, we call writeFile with the imageData and 'binary' to write the file as binary data to logo.png.

The end event is emitted when the data is done reading.

Conclusion

To write an image to a local server with Node.js, we can use the fs.writeFile method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *