Categories
JavaScript Answers

How to get connection status on Socket.io client with JavaScript?

To get connection status on Socket.io client with JavaScript, we use the socket.connected property.

For instance, we write

const socket = io.connect();
console.log("check 1", socket.connected);
socket.on("connect", () => {
  console.log("check 2", socket.connected);
});

to get the connection status from the socket.connected boolean variable.

If it’s true, then the client is connected.

Categories
JavaScript Answers

How to fix ECONNREFUSED for Postgres on Node.js with error Docker?

To fix ECONNREFUSED for Postgres on Node.js with error Docker, we make sure the connection string is correct.

For instance, we write

DATABASE_URL: postgres://username:pgpassword@db:5432/mydatabase

to set the DATABASE_URL environment variable to a connection string for postgres.

We add the username and password with the database name in the string.

Categories
JavaScript Answers

How to properly add 1 month from now to current date in moment.js and JavaScript?

To properly add 1 month from now to current date in moment.js and JavaScript, we call the add method.

For instance, we write

const d = moment().add(1, "months").calendar();

to call moment to create a moment object with the current date and time.

Then we call add to add 1 month to the date.

And we call calendar to return the date string with the date.

Categories
JavaScript Answers

How to check if a variable exists with Node Jade Template Engine?

To check if a variable exists with Node Jade Template Engine, we use an if statement.

For instance, we write

if locals.username
  p= username
else
  p No Username!

to check is the locals.username variable exists with if locals.username.

Categories
JavaScript Answers

How to send a success status to browser from Node.js and Express?

To send a success status to browser from Node.js and Express, we call the sendStatus method.

For instance, we write

res.sendStatus(200)

to call the sendStatus method to send a 200 response code.