Categories
JavaScript Answers

How to use multiple parameters in URL in Node.js Express?

To use multiple parameters in URL in Node.js Express, we add multiple parameter placeholders.

For instance, we write

app.get("/fruit/:fruitName/:fruitColor", (req, res) => {
  const data = {
    fruit: {
      apple: req.params.fruitName,
      color: req.params.fruitColor,
    },
  };

  send.json(data);
});

to add the fruitName and fruitColor URL placeholders for the get route.

Then we get their values from the req.params object.

Categories
JavaScript Answers

How to start a Node.js server as a daemon process?

To start a Node.js server as a daemon process, we use the forever package.

For instance, we run

npm install -g forever

to install forever globally.

Then we run it by running

forever start server.js

We run server.js as a daemon with forever start.

Categories
JavaScript Answers

How to fix “Cannot find module ‘ts-node/register'” error with JavaScript?

To fix "Cannot find module ‘ts-node/register’" error with JavaScript, we install the ts-node package.

To install it, we run

npm install ts-node --save-dev

to save the ts-node package as a dev dependency.

Categories
JavaScript Answers

How to fix nodemon not found in npm with JavaScript?

To fix nodemon not found in npm with JavaScript, we install nodemon.

To install it, we run

npm install nodemon --save 

Then we add

{
  //...
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon app.js"
  }
  //...
}

in package.json to add the start script to run app.js with nodemon.

Then we run

npm start

to start the script.

Categories
JavaScript Answers

How to use socket.io in Express 4 and express-generator’s /bin/www with JavaScript?

To use socket.io in Express 4 and express-generator’s /bin/www with JavaScript, we create a module with the socket.io code.

For instance, we write

const io = require("socket.io")();
const socketApi = {
  io,
};

io.on("connection", (socket) => {
  console.log("A user connected");
});

module.exports = socketApi;

in socketApi.js to listen for client connections by call on with 'connection' and the event handler.

We export the socketApi object with the io object.

Then we write

const app = require("../app");
const debug = require("debug")("socketexpress:server");
const http = require("http");
const socketApi = require("../socketApi");

const port = normalizePort(process.env.PORT || "3000");
app.set("port", port);

const server = http.createServer(app);
socketApi.io.attach(server);

to import the socketApi file with require("../socketApi").

Then we call socketApi.io.attach to attach the Express server to it.