Categories
JavaScript Answers

How to write JSON object to a JSON file with Node.js fs.writeFileSync?

To write JSON object to a JSON file with Node.js fs.writeFileSync, we call JSON.stringify.

For instance, we write

const fs = require("fs");
const content = JSON.stringify(output);

fs.writeFileSync("/tmp/phraseFreqs.json", content);

to call JSON.stringift to coinvert the output object to a JSON string.

Then we call writeFileSync with the path to write to and the stringified JSON object content to write the JSON to the file.

Categories
JavaScript Answers

How to see the SQL generated by Node Sequelize.js?

To see the SQL generated by Node Sequelize.js,. we set the logging option.

For instance, we write

const sequelize = new Sequelize("database", "username", "password", {
  logging: console.log,
});

to set the logging property to log with console.log.

We can also write

const sequelize = new Sequelize("database", "username", "password", {
  logging: (str) => {
    // do your own logging
  },
});

to log with our own logging function.

Categories
JavaScript Answers

How to redirect to URL with Node.js?

To redirect to URL with Node.js, we use the res.redirect method.

For instance, we write

res.redirect("your/404/path.html");

to call res.redirect with the path to redirect to with Express.

Categories
JavaScript Answers

How to add a single routing handler for multiple routes in a single line with Node.js Express.js?

To add a single routing handler for multiple routes in a single line with Node.js Express.js, we call the route method with an array of routes.

For instance, we write

app.get(
  [
    "/test",
    "/alternative",
    "/bar*",
    "/foo/:farcus/",
    "/hoop(|la|lapoo|lul)/poo",
  ],
  (request, response) => {}
);

to create a get route handler that accepts requests from the URLs listed in the array.

Categories
JavaScript Answers

How to pipe a stream to s3.upload() with Node.js?

To pipe a stream to s3.upload() with Node.js, we call the stream.PassThrough constructor.

For instance, we write

const uploadFromStream = (s3) => {
  const pass = new stream.PassThrough();
  const params = { Bucket: BUCKET, Key: KEY, Body: pass };
  s3.upload(params, (err, data) => {
    console.log(err, data);
  });

  return pass;
};

inputStream.pipe(uploadFromStream(s3));

to define the uploadFromStream function.

In it, we create a PassThrough object.

Then we call upload with the params object to upload the stream data.

Next, we call pipe with the PassThrough object returned by uploadFromStream to upload the inputStream data.