Search code examples
javascriptnode.jshttpfs

Nodejs Missing Data From HTTP Request


I am currently trying to get a file from a HTTP request and then write the data to a file (in this case a PDF).

Using the following I can generate a valid PDF but the file I send has a few lines but the file I create is blank.

The function I am using to try and get the data:

async function getDataFromReq(req){
    let body = '';
    await req.on('data', (chunk) => {
        body += chunk;
    });
    return body;
}

My implementation of that function and writing it to a file:

let file = await getDataFromReq(req);
await writeFile(fileName,file);

My write file function:

async function writeFile(fileName,file){
    fs.writeFileSync('./'+fileName, file);
}

Note:

I was able to use King Friday's solution but I took Quentins's advice and used existing libraries to do the task instead of reinventing the wheel. I used multer following this guide - https://bezkoder.com/node-js-express-file-upload/


Solution

  • Like so

    const { promises as fs } = require('fs');
    
    function getDataFromReq(req) {
      return new Promise((resolve, reject) => {
        let body = '';
        req.on('data', chunk => {
          body += chunk;
        });
        req.on('end', () => {
          resolve(body);
        });
        req.on('error', err => {
          reject(err);
        });
      });
    });
    
    

    Then you can use in an async method like so...

    const body = await getDataFromReq(req);
    await fs.writeFile(fileName, body);