Categories
JavaScript Answers

How to watch directory for changes with nodemon?

To watch directory for changes with nodemon, we use the --watch option.

For instance, we run

nodemon --watch src server.js

to use the --watch option to watch the src folder for changes when running server.js.

Categories
JavaScript Answers

How to listen all interfaces instead of localhost only with Node Express app server?

To listen all interfaces instead of localhost only with Node Express app server, we call listen with '0.0.0.0'.

For instance, we write

const express = require("express");
const app = express();
app.listen(3000, "0.0.0.0");

to call app.listen with "0.0.0.0" to listen for all interfaces at port 3000.

Categories
JavaScript Answers

How to overwrite a file using fs in Node.js?

To overwrite a file using fs in Node.js, we set the 'w' flag.

For instance, we write

fs.writeFileSync(path, content, { encoding: "utf8", flag: "w" });

to call writeFileSync with an object with the flag property set to 'w' to overwrite the file at path with the content string.

Categories
JavaScript Answers

How to set a base URL for NodeJS app?

To set a base URL for NodeJS app, we create a router object.

For instance, we write

const express = require("express");
const app = express();
const router = express.Router();

router.use((req, res, next) => {
  console.log("%s %s %s", req.method, req.url, req.path);
  next();
});

router.use("/bar", (req, res, next) => {
  next();
});

router.use((req, res, next) => {
  res.send("Hello World");
});

app.use("/foo", router);

app.listen(3000);

to create a router with express.Router.

Then we call use to add the route middlewares.

Next, we call app.use with the base URL and the router to add the routes for the base path.

Categories
JavaScript Answers

How to fix the Node.js 17.0.1 Gatsby error – “digital envelope routines::unsupported … ERR_OSSL_EVP_UNSUPPORTED” error?

To fix the Node.js 17.0.1 Gatsby error – "digital envelope routines::unsupported … ERR_OSSL_EVP_UNSUPPORTED" error, we use a legacy SSL provider to let us use the SSL algorithm or key size used by Gatsby.

For instance, we write

{
  "scripts": {
    "build": "export NODE_OPTIONS=--openssl-legacy-provider; gatsby build"
  }
}

in package.json rto modify the build script to set the NODE_OPTIONS environment variable to --openssl-legacy-provider to use an old version of OpenSSL to let Gatsby use an old algorithm or key size.