kota's memex

The main concept in CommonJS modules is a function called require. When you call this with the module name of a dependency, it makes sure the module is loaded and returns its interface. The loaded wraps the module in a function so modules automatically get their own local scope.

This whole system is a hack because the language never properly supported module. These days ECMAScript modules exist which is a big improvement.

// This example module provides a date-formatting function. It uses two packages
// from npm; ordinal to convert numbers to strings like "1st" and "2nd", and
// date-names to get the English named for weekdays and months. It exports a
// single function, formatDate, which takes a Date object and a template string.
//
// The template string may contain codes that direct the format such as YYYY for
// the full year and Do for the ordinal day of the month. You could give it a
// string like "MMMM Do YYYY" to get "November 22nd 2019".
const ordinal = require("ordinal")
const {days, months} = require("date-names")

exports.formatDate = function(date, format) {
	return format.replace(/YYYY|M(MMM)?|Do|dddd/g, tag => {
		if (tag == "YYYY") return date.getFullYear()
		if (tag == "M") return date.getMonth()
		if (tag == "MMMM") return months[date.getMonth()]
		if (tag == "D") return date.getDate()
		if (tag == "Do") return ordinal(date.getDate())
		if (tag == "dddd") return days[date.getDay()]
	})
}

Note how the interface of ordinal is a single function whereas date-names exports an object containing multiple things, days and months are arrays of names.