Categories
JavaScript Answers

How to create a file only if it doesn’t exist in Node.js?

To create a file only if it doesn’t exist in Node.js, we call the readFile and writeFile methods.

For instance, we write

import * as fs from "fs";

const upsertFile = async (name) => {
  try {
    await fs.promises.readFile(name);
  } catch (error) {
    await fs.promises.writeFile(name, "");
  }
};

to define the upsertFile function.

In it, we call readFile with the file name path to check if the file exists.

If it doesn’t exist, an error is thrown and the catch block is run.

In the catch block, we call writeFile to write the at the name path.

Categories
JavaScript Answers

How to enable cross-origin resource sharing (CORS) in the Express.js framework on Node.js?

To enable cross-origin resource sharing (CORS) in the Express.js framework on Node.js, we add some response headers.

For instance, we write

app.all("/", (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
});

app.get("/", (req, res, next) => {
  // Handle the get for this route
});

app.post("/", (req, res, next) => {
  // Handle the post for this route
});

to call res.header to add the Access-Control-Allow-Origin and Access-Control-Allow-Header response headers to enable CORS.

Then we routes to handle get and post requests from the / URL.

Categories
JavaScript Answers

How to differentiate clients with webSocketServer in Node.js?

To differentiate clients with webSocketServer in Node.js, we canm use the sec-websocket-key header.

For instance, we write

wss.on("connection", (ws, req) => {
  ws.id = req.headers["sec-websocket-key"];

  //...
});

to listen to the connection event with on.

And we get the sec-websocket-key header with req.headers["sec-websocket-key"] in the event handler to get the client’s ID.

Categories
JavaScript Answers

How to write objects into file with Node.js?

To write objects into file with Node.js, we call the writeFileSync method.

For instance, we write

fs.writeFileSync("./data.json", JSON.stringify(obj, null, 2), "utf-8");

to call the writeFileSync method to write the stringified obj object to data.json.

We convert obj to a JSON string with JSON.stringify.

Categories
JavaScript Answers

How to get raw request body using Express with Node.js?

To get raw request body using Express with Node.js, we use the req.body property.

For instance, we write

const bodyParser = require("body-parser");
app.use(bodyParser.raw(options));

app.get(path, (req, res) => {
  console.log(req.body);
  //...
});

to call app.get to create a route handler for the path path.

Then we get the request body with req.body.

req.body is a buffer object.

We use the bodyParser.raw middleware to parse the request body into a buffer.