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.

Categories
JavaScript Answers

How to write an array to file with Node.js?

To write an array to file with Node.js, we call the writeFile method.

For instance, we write

require("fs").writeFile("./my.json", JSON.stringify(myArray), (err) => {
  if (err) {
    console.error("error");
  }
});

to call writeFile with the file path and a stringified version of the myArray array to write the content of myArray into the my.json file.

Categories
JavaScript Answers

How to execute PHP scripts within Node.js web server?

To execute PHP scripts within Node.js web server, we call the exec function.

For instance, we write

const exec = require("child_process").exec;

app.get("/", (req, res) => {
  exec("php index.php", (error, stdout, stderr) => {
    res.send(stdout);
  });
});

to call exec to run index.php with php.

We get the output from the stdout parameter in the callback.