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.

Categories
JavaScript Answers

How to save multiple documents concurrently in Mongoose and Node.js?

To save multiple documents concurrently in Mongoose and Node.js, we call the create method.

For instance, we write

const array = [{ type: "jelly bean" }, { type: "snickers" }];
Candy.create(array, (err, jellybean, snickers) => {
  if (err) {
    //...
  }
});

to call the create method with the array to write the entries into the collection.

And then we get the written entries from the parameters after err.

err is the error if there is any.