The Node.js
library has become the standard platform for creating server-side and network-based applications. Can functional programming be used for server-side application programming? Yes! Ok, but do there exist any functional libraries that are designed for this performance-critical environment? The answer to that is also: yes.
All the functional libraries outlined in this chapter will work in the Node.js
library, and many depend on the browserify.js
module to work with browser elements.
In our brave new world of network systems, server-side application developers are often concerned with concurrency, and rightly so. The classic example is an application that allows multiple users to modify the same file. But if they try to modify it at the same time, you will get into an ugly mess. This is the maintenance of state problem that has plagued programmers for decades.
Assume the following scenario:
For a long time, the solution to this problem was to create a state about the file. Toggle a lock status to on when someone begins editing it, which prevents others from being able to edit it, and then toggle it to off once they save it. In our scenario, Billy would not be able to do his work until Adam gets back from lunch. And if it's never saved (if, say, Adam decided to quit his job in the middle of the lunch break), then no one will ever be able to edit it.
This is where functional programming's ideas about immutable data and state (or lack thereof) can really be put to work. Instead of having users modify the file directly, with a functional approach they would modify a copy of the file, which is a new revision. If they go to save the revision and a new revision already exists, then we know that someone else has already modified the old one. Crisis averted.
Now the scenario from before would unfold like this:
This is known as event sourcing. There is no explicit state to be maintained, only events. The process is much cleaner and there is a clear history of events that can be reviewed.
This idea and many others are why functional programming in server-side environments is on the rise.