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 chunk
s 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.