Categories
JavaScript Answers

How to serve an image using Node.js?

Sometimes, we want to serve an image using Node.js.

In this article, we’ll look at how to serve an image using Node.js.

How to serve an image using Node.js?

To serve an image using Node.js, we can use the middleware returned by express.static.

For instance, we write

const path = require('path');
const express = require('express');
const app = express();

const dir = path.join(__dirname, 'public');

app.use(express.static(dir));

app.listen(3000, () => {
  console.log('Listening on http://localhost:3000/');
});

to call app.use with the middleware returned by express.static called with the dir of the image files.

This will expose the dir folder to the public.

Conclusion

To serve an image using Node.js, we can use the middleware returned by express.static.

Categories
JavaScript Answers

How to read the contents of a Node.js stream into a string variable?

Sometimes, we want to read the contents of a Node.js stream into a string variable.

In this article, we’ll look at how to read the contents of a Node.js stream into a string variable.

How to read the contents of a Node.js stream into a string variable?

To read the contents of a Node.js stream into a string variable, we can use the Buffer.concat method.

For instance, we write

const chunks = [];

readStream.on("data", (chunk) => {
  chunks.push(chunk);
});

readStream.on("end", () => {
  res.send(Buffer.concat(chunks));
});

to push the chunk into chunks when data received in the data event callback.

Then we call Buffer.concat with chunks to combine the chunks in the end event callback when we’re done reading the stream to return a file.

Conclusion

To read the contents of a Node.js stream into a string variable, we can use the Buffer.concat method.

Categories
JavaScript Answers

How to add logging with Node.js?

Sometimes, we want to add logging with Node.js.

In this article, we’ll look at how to add logging with Node.js.

How to add logging with Node.js?

To add logging with Node.js, we can use the winston package.

We install it by running

npm i winston

Then we use it by writing

const winston = require('winston');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  defaultMeta: {
    service: 'user-service'
  },
  transports: [
    new winston.transports.File({
      filename: 'error.log',
      level: 'error'
    }),
    new winston.transports.File({
      filename: 'combined.log'
    }),
  ],
});

We create a new winston logger using the winston.Logger constructor.

We call the constructor with an object that lets us set the transports option to specify where to write the log output.

The transports option is set to an array that specifies we write log items with level error to error.log.

And we write everything else to combined.log.

The format is set to winston.format.json so the log entries are in JSON format.

And the default log item level is 'info'.

We then log entries with

logger.info('log to file');

to log something with level info.

Conclusion

To add logging with Node.js, we can use the winston package.

Categories
JavaScript Answers

How to use Node.js and socket.io with SSL?

Sometimes, we want to use Node.js and socket.io with SSL.

In this article, we’ll look at how to use Node.js and socket.io with SSL.

How to use Node.js and socket.io with SSL?

To use Node.js and socket.io with SSL, we can set the secure option to true when we call io.connect.

For instance, we write

const socket = io.connect('https://localhost', {
  secure: true
});

to call io.connect with the socket.io server URL and the secure option set to true to connect via SSL.

Conclusion

To use Node.js and socket.io with SSL, we can set the secure option to true when we call io.connect.

Categories
JavaScript Answers

How to use Node.js filesystem with async / await?

Sometimes, we want to use Node.js filesystem with async / await.

In this article, we’ll look at how to use Node.js filesystem with async / await.

How to use Node.js filesystem with async / await?

To use Node.js filesystem with async / await, we can use the fs.promises module.

For instance, we write

import fs from 'fs';
const fsPromises = fs.promises;

const listDir = async () => {
  try {
    return fsPromises.readdir('path/to/dir');
  } catch (err) {
    console.error('Error occured while reading directory!', err);
  }
}

listDir();

to define the listDir function that calls fsPromises.readdir with the path we want to list.

We use await to get the result resolved by the promise returned.

And we use try and catch to catch any errors if the promise is rejected.

Conclusion

To use Node.js filesystem with async / await, we can use the fs.promises module.