Categories
Node.js Tips

Node.js Tips — File Size, Plain Text Request Body, Sen

Spread the love

Like any kind of apps, there are difficult issues to solve when we write Node apps.

In this article, we’ll look at some solutions to common problems when writing Node apps.

Force Parse Request Body as Plain Text Instead of JSON in Express

We can remove the body-parser middleware to parse the request body as raw text.

For instance, we can write:

const express = require('express');

const app = express();

const parseRawBody = (req, res, next) => {
  req.setEncoding('utf8');
  req.rawBody = '';
  req.on('data', (chunk) => {
    req.rawBody += chunk;
  });
  req.on('end', () => {
    next();
  });
}

app.use(parseRawBody);

app.post('/test', (req, res) => {
  res.send(req.rawBody);
});

app.listen(3000);

We created our own parseRawBody middleware that takes the request, response objects and the next function.

req is the request, which is a read stream.

We can get the data from it by listening to the data event.

In the handler for the data event, we concatenate the chunks of text to the req.rawBody property.

Then when the end event is emitted, then the stream has no more data to emit, so we call next to move to the next middleware.

Then we can access req.rawBody in the routes that come after it.

If we use the body-parser package, then we can use the bodyParser.text() middleware to keep the request body as plain text.

For instance, we can write:

app.use(bodyParser.text());

Then we can access the request body by writing:

app.get('/', (req, res) => {
  res.send(req.body);
})

req.body has the string with the request body.

Sending Message to a Specific Client with Socket.io and Empty Message Queue

To send a message to a specific client and empty the message queue with socket.io, we can listen to the connection event and then set the socket object as the property of an object.

For instance, we can write:

const socketio = require('socket.io');
const clients = {};
const io = socketio.listen(app);

io.sockets.on('connection', (socket) => {
  clients[socket.id] = socket;
});

The property name is the socket’s ID, indicated by the socket.id property.

We saved each client’s socket so that we can call emit to send a message to the client later.

Then we can send a message by writing:

const socket = clients[socketId];
socket.emit('show', {});

Where socketId is the ID of the socket that we set earlier.

We call emit with our own event and data we want to send.

Modifying Express Request Object

To modify the Express’s request object, we can assign our properties in the request object.

For instance, we can write:

app.use((req, res, next) => {
  req.root = `${req.protocol}://${req.get('host')}`;
  next();
});

We set the req.root property to the protocol and host of the URL combined.

The callback is a middleware that we can use anywhere.

next is a function that calls the next middleware in the chain.

Find the Size of the File in Node.js

We can find the size of a file with stateSync .

For instance, we can write:

function getFileSize(filename) {
  const stats = fs.statSync(filename);
  const fileSizeInBytes = stats.size;
  return fileSizeInBytes;
}

We call statsSync on the filename parameter, which is the string path to a file.

Then we can get the size in bytes with the size property.

We can also use the filesize package to get the file size.

For instance, we can write:

const filesize = require("filesize");
const stats = fs.statSync("foo.txt");
const fileSizeInMb = filesize(stats.size, {round: 0});

The benefit of this package is that we can conveyor the size to whatever format we like.

For instance, we can change the base, convert it to an object, and much more.

The example above converted the size to the file size in megabytes.

We can do other conversions by writing:

const filesize = require("filesize");
const stats = fs.statSync("foo.txt");
const fileSizeMb = filesize(stats.size, {round: 0});
const fileSizeArray = filesize(stats.size, {output: "array"});
const fileSizeObj = filesize(stats.size, {output: "object"});

The array has the size and unit as separate entries of the array.

object puts the size, union, exponent in their own properties.

Conclusion

We can keep the request body text in various ways.

There are libraries to help us get the file size in the format we want.

We can send messages to a specific client with Socket.io.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *