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.

Categories
JavaScript Answers

How to use the Node.js PostgreSql module?

To use the Node.js PostgreSql module, we create a connection pool.

For instance, we write

const { Pool } = require("pg");

const pool = new Pool({
  connectionString: DATABASE_URL,
  ssl: false,
  max: 20,
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 2000,
});
module.exports = {
  query: (text, params) => pool.query(text, params),
};

to create a new Pool object to to create the connection pool.

Then we call pool.query to make a query to the database with the text SQL command and params parameters.

Categories
JavaScript Answers

How to fix 404 when attempting to publish new package to NPM?

To fix 404 when attempting to publish new package to NPM, we log into npm before publishing.

To do this, we run

npm login

to log into npm to publish the package.