Qubyte Codes

A recent contribution I made for Node.js

Published

I've made a couple of small contributions to Node.js in the past. These were quite esoteric, and unlikely to be discovered or noticed by most developers. Recently I made a contribution which might be noticed though.

Most Node developers are familiar with Express. When responding to a client request in Express, chaining makes setting the status and sending a body fluent. It is possible to chain the call to send after the call to status because status returns res.

// Express version.
function requestHandler(req, res) {
  res.status(200).send('Hello, world!');
}

The vanilla Node analogue is a little more verbose because writeHead had no explicit return (which means it returned undefined).

// Vanilla Node.
function requestHandler(req, res) {
  res.writeHead(200);
  res.end('Hello, world!');
}

I find the repetition a little annoying, and frequently tried to chain the call to end onto the call to writeHead by mistake.

My contribution was to make writeHead return the response object res, to enable method chaining.

// Node 11.10.0+
function requestHandler(req, res) {
  res.writeHead(200).end('Hello, world!');
}

This makes the vanilla Node API for server responses just a little more friendly.