Categories
JavaScript Answers

How to get data out of a Node.js http get request?

To get data out of a Node.js http get request, we listen for the data event.

For instance, we write

require("http").get("http://httpbin.org/ip", (res) => {
  res.setEncoding("utf8");
  res.on("data", (body) => {
    console.log(body);
  });
});

to call res.on to listebn to the data event.

We get the response body from the body parameter in the callback.

Categories
JavaScript Answers

How to make a https post in Node.js without any third party module?

To make a https post in Node.js without any third party module, we use fetch.

For instance, we write

const res = await fetch("https://nodejs.org/api/documentation.json");
if (res.ok) {
  const data = await res.json();
  console.log(data);
}

to call fetch to make a get request to the URL.

We get the JSON response with res.json.

We check if the request works with res.ok.

fetch is built into Node.js since version 18.

Categories
JavaScript Answers

How to pass JSON to HTTP POST Request with JavaScript?

To pass JSON to HTTP POST Request with JavaScript, we call request with an object with the json property.

For instance, we write

request({
  url,
  method: "POST",
  json: requestData,
});

to call request to make a post request to the url.

We set json to requestData JSON string to send the JSON.

Categories
JavaScript Answers

How to add asynchronous Node.js module exports?

To add asynchronous Node.js module exports, we use promises.

For instance, we write

module.exports = (async () => {
  const db = await require("./db");
  const foo = "bar";

  return {
    foo,
  };
})();

in foo.js to export the promise returned by the async function.

Then we import it by writing

(async () => {
  const foo = await require("./foo");
  console.log(foo);
})();

to call require to require foo.js, which exported the promise returned by the async function.

We use await to get the object returned by the promise.

Categories
JavaScript Answers

How to append binary data to a buffer in Node.js?

To append binary data to a buffer in Node.js, we call the Buffer.concat method.

For instance, we write

const newBuffer = Buffer.concat([buffer1, buffer2]);

to call Buffer.concat with an array of buffers to return a new buffer that are combined from the buffers in the array.