Categories
JavaScript Answers

How to fix Babel 7 – ReferenceError: regeneratorRuntime is not defined with JavaScript?

To fix Babel 7 – ReferenceError: regeneratorRuntime is not defined with JavaScript, we install a few packages and then import them into our project.

We install the missing packages with

npm install --save core-js
npm install --save regenerator-runtime    

And then import them with

import "core-js/stable";
import "regenerator-runtime/runtime";

to let us use Babel in our project.

Categories
JavaScript Answers

How to specify the path of package.jso to npm with JavaScript?

To specify the path of package.jso to npm with JavaScript, we set the --prefix option.

For instance, we run

npm --prefix /path/to/project run build

to set the --prefix option to the path of package.json we want npm to read from when running the build command.

Categories
JavaScript Answers

How to use specific middleware in Express for all paths except a specific one with Node.js?

To use specific middleware in Express for all paths except a specific one with Node.js, we can check the path of the request in the middleware function.

For instance, we write

const checkUser = (req, res, next) => {
  if (req.path == "/") {
    return next();
  }
  next();
};

app.all("*", checkUser);

to call app.all to add the checkUser middleware for all routes.

In checkUser, we check the path of the request with req.path.

If it’s '/', we call the next middleware with next and return to end the execution of checkUser.

Categories
JavaScript Answers

How to add route with optional parameter after root in Node.js Express?

To add route with optional parameter after root in Node.js Express, we add a question mark after the route parameter placeholder.

For instance, we write

app.get("/api/v1/tours/:cId/:pId/:batchNo?", (req, res) => {
  console.log(req.params.cId);
  console.log(req.params.pId);
  console.log(req.params.batchNo);
});

to add the option batchNo route parameter.

We get its value from req.params.batchNo.

Categories
JavaScript Answers

How to add Gzip compression with Node.js?

To add Gzip compression with Node.js, we use the compression package.

To install it, we run

npm install compression

Then we use it by writing

const express = require("express");
const compression = require("compression");

const app = express();
app.use(compression());

to call app.use with the middleware returned by the compression function to add gzip compression to our Express app.