I have a node.js app and I am writing response data to a file from http request. So far what I found how to do that is as follows.
import fs from 'node:fs/promises'
import http from 'http'
const fetch = async () => {
const url = 'http://localhost'
let filePath = 'myfile'
let file: fs.FileHandle | undefined
let resolve = () => {}
const promise = new Promise<void>((r) => (resolve = r))
try {
file = await fs.open(filePath, 'a')
const writable = file.createWriteStream()
let httpCode: number | undefined
const req = http
.request(url, (res) => {
httpCode = res.statusCode
if (httpCode === 200) {
res.pipe(writable)
}
})
.on('error', function (err) {
console.log(err)
})
writable.on('error', (err) => {
console.log(err)
})
req.on('close', () => {
writable.close()
resolve()
})
req.end()
await promise
} finally {
if (file) {
await file.close()
}
}
}
fetch()
I am satisfied with everything but one. According to event unpipe
:
This is also emitted in case this Writable stream emits an error when a Readable stream pipes into it.
This makes me assume that if the pipe breaks because errors on the writable. Then readable
is stopped to be managed by pipe. With that according to http.ClientRequest
:
If a 'response' event handler is added, then the data from the response object must be consumed
According to this in even of the writable issuing an error the response object in the request handler might get stuck with data and never exit. Does some correct error handling is required on writable? Or am I reading it wrong?