0

I need to send a file as part of a POST request in Node.js and I don't want to use other packages or external libraries but plain http (https) module, part of the standard Node.js API.

From the Node.js doc, an example

This example in the Node.js doc, hints about what I want to achieve:

const postData = querystring.stringify({'msg': 'Hello World!'});

const options = {
  hostname: 'http://localhost',
  port: 8080,
  path: '/upload',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': Buffer.byteLength(postData)
  }
};

const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
  res.on('end', () => {
    console.log('No more data in response.');
  });
});

req.on('error', (e) => {
  console.error(`problem with request: ${e.message}`);
});

// Write data to request body
req.write(postData);
req.end();

What I want

This example is very close to what I want to achieve, the only difference is in the very first lines:

const postData = querystring.stringify({'msg': 'Hello World!'}); // <== I want to send a file

Instead of sending a string, I want to send a file. The doc page says that it should be possible:

http.request() returns an instance of the http.ClientRequest class. The ClientRequest instance is a writable stream. If one needs to upload a file with a POST request, then write to the ClientRequest object.

How can I do this?


Attempts

I have tried:

clientRequest.write(fs.createReadStream("C:/Users/public/myfile.txt"));
clientRequest.end();

But I get this error:

TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string or Buffer. Received type object

Andry
  • 16,172
  • 27
  • 138
  • 246
  • @LawrenceCherone No unfortunately because it uses the (deprecated) module `request` and not `http`. – Andry Mar 28 '20 at 21:12
  • 1
    Ok this one, https://stackoverflow.com/questions/18936561/how-to-upload-file-using-a-post-request-in-the-node-http-library the idea is the same, load file into buffer you cant use a stream. – Lawrence Cherone Mar 28 '20 at 21:13
  • @LawrenceCherone Yes... it does I think :) – Andry Mar 28 '20 at 21:14
  • How is it I could not find it!!! I have been searching in StackOverflow for 2 hours for a similar question – Andry Mar 28 '20 at 21:15

1 Answers1

0

I'm not sure if you're using the streams correctly. Try this:

fs.createReadStream(filePath).pipe(req);
Merve Sahin
  • 1,008
  • 2
  • 14
  • 26