Categories
JavaScript Answers

How to stop Mongoose from adding an s at the end of a collection name?

Sometimes, we want to stop Mongoose from adding an s at the end of a collection name.

In this article, we’ll look at how to stop Mongoose from adding an s at the end of a collection name.

How to stop Mongoose from adding an s at the end of a collection name?

To stop Mongoose from adding an s at the end of a collection name, we can set the collection property when we create the schema.

For instance, we write

const dataSchema = new Schema({
  //..
}, {
  collection: 'data'
})

to create a Schema instance with an object that sets the collection property.

The collection property is set to the name we want for the collection.

Conclusion

To stop Mongoose from adding an s at the end of a collection name, we can set the collection property when we create the schema.

Categories
JavaScript Answers

How to remove all files from directory without removing directory in Node.js?

Sometimes, we want to remove all files from directory without removing directory in Node.js.

In this article, we’ll look at how to remove all files from directory without removing directory in Node.js.

How to remove all files from directory without removing directory in Node.js?

To remove all files from directory without removing directory in Node.js, we can use the readdir method to get an array of file paths in the directory.

Then we can use unlink to remove all the files.

For instance, we write

const fs = require('fs');
const path = require('path');

const directory = 'test';

fs.readdir(directory, (err, files) => {
  if (err) {
    throw err;
  }

  for (const file of files) {
    fs.unlink(path.join(directory, file), err => {
      if (err) {
        throw err;
      }
    });
  }
});

to call readdir to get an array of files.

Then we loop through the files in the for-of loop.

In the loop body, we call fs.unlink with the path of each file returned by path.join to remove them.

Conclusion

To remove all files from directory without removing directory in Node.js, we can use the readdir method to get an array of file paths in the directory.

Then we can use unlink to remove all the files.

Categories
JavaScript Answers

How to set custom favicon in Express?

Sometimes, we want to set custom favicon in Express.

In this article, we’ll look at how to set custom favicon in Express.

How to set custom favicon in Express?

To set custom favicon in Express, we can use the server-favicon package.

To install it, we run

npm i server-favicon

Then we use it by writing

const favicon = require('serve-favicon');
const path = require('path');

//...

app.use(favicon(path.join(__dirname, 'public', 'images', 'favicon.ico')));

to call app.use with the middleware returned by favicon.

We call favicon with the path to the favicon.

Conclusion

To set custom favicon in Express, we can use the server-favicon package.

Categories
JavaScript Answers

How to authenticate socket.io connections using JWT?

Sometimes, we want to authenticate socket.io connections using JWT.

In this article, we’ll look at how to authenticate socket.io connections using JWT.

How to authenticate socket.io connections using JWT?

To authenticate socket.io connections using JWT, we send the token with the socket.io client.

And then on the server, we check the token.

For instance, we write

const {
  token
} = sessionStorage;
const socket = io.connect('http://localhost:3000', {
  query: {
    token
  }
});

to call io.connect to connect to the server.

We set the query.token property to send the auth token.

Then on the server, we write

const io = require('socket.io')();
const jwt = require('jsonwebtoken');

io.use((socket, next) => {
    if (socket.handshake?.query?.token) {
      jwt.verify(socket.handshake?.query?.token, 'SECRET_KEY', (err, decoded) => {
        if (err) {
          return next(new Error('Authentication error'));
        }
        socket.decoded = decoded;
        next();
      });
    } else {
      next(new Error('Authentication error'));
    }
  })
  .on('connection', (socket) => {
    socket.on('message', (message) => {
      io.emit('message', message);
    });
  });

to get the token with socket.handshake?.query?.token.

If it’s present, we check it with the jwt.verify method from the jsonwebtoken package against the private SECRET_KEY.

If auth is successful, err is null. And we call next with nothing.

Otherwise, we throw an error if the token isn’t present or when err is set.

Next, we call on with 'connection' to emit a message when connection succeeds.

Conclusion

To authenticate socket.io connections using JWT, we send the token with the socket.io client.

And then on the server, we check the token.

Categories
JavaScript Answers

How to add basic HTTP authentication with Node and Express 4?

Sometimes, we want to add basic HTTP authentication with Node and Express 4.

In this article, we’ll look at how to add basic HTTP authentication with Node and Express 4.

How to add basic HTTP authentication with Node and Express 4?

To add basic HTTP authentication with Node and Express 4, we can create our own middleware.

For instance, we write

app.use((req, res, next) => {
  const auth = {
    login: 'yourlogin',
    password: 'yourpassword'
  }
  const [, b64auth = ''] = (req.headers.authorization || '').split(' ')
  const [login, password] = Buffer.from(b64auth, 'base64').toString().split(':')
  if (login && password && login === auth.login && password === auth.password) {
    return next()
  }
  res.set('WWW-Authenticate', 'Basic realm="401"')
  res.status(401).send('Authentication required.')
})

to call app.use with a callback that checks if username 'yourlogin' and password 'password' received.

We check the username and password with

const [login, password] = Buffer.from(b64auth, 'base64').toString().split(':')

and

login && password && login === auth.login && password === auth.password

Then we call next to call the next middleware that we call when authentication succeeds.

Otherwise, we call res.set and res.status to return a 401 response.

Conclusion

To add basic HTTP authentication with Node and Express 4, we can create our own middleware.