I would like to get upload progress information during http post request using node js http. my code is simple and it works but I am only notified when there is an error or the upload is completed. But I need to show a progress bar to the user and to do that I need to check the progress every second or so. Basically I need to have upload speed and how much of the file has been uploaded at given time.
const http = require('http');
const fs = require('fs');
const FormData = require('form-data');
function myUploadFunction(authToken,uploadPath, file) {
const form = new FormData();
form.append('file', fs.createReadStream(file.path));
form.append('filename', file.name);
form.append('parent_dir', '/');
const requestHeaders = {
Accept: '*/*',
Authorization: `Token ${authToken}`,
};
const options = {
host: 'myHost',
port: 'myPort',
path: uploadPath,
method: 'POST',
headers: requestHeaders,
};
form.submit(options, (error, response) => {
response.setEncoding('utf8');
response.on('data', (chunk) => {
// this code runs only when the upload is completed and the server only send some info about the file. And only if this info is large it will send it in chunks
logger.debug(`BODY: ${chunk}`);
});
response.on('end', () => {
logger.debug('No more data in response.');
});
});
}
When I upload a file, nothing happens till upload is completed then I get the response and it executes response.onData and afetr that response.onEnd.