Express is a web application framework for Node.js, modeled after the Ruby project Sinatra.[66] Express provides a lot of the plumbing code that you’d otherwise end up writing yourself. To see why, let’s take a look at a basic Node.js server using only the http module.
| | 'use strict'; |
| | const http = require('http'); |
| | const server = http.createServer((req, res) => { |
| | res.writeHead(200, {'Content-Type': 'text/plain'}); |
| | res.end('Hello World\n'); |
| | }); |
| | server.listen(60700, () => console.log('Ready!')); |
This is quite similar to creating a basic TCP server using the net module like you did way back in Chapter 3, Networking with Sockets. We bring in the http module, call its createServer() method with a callback, and finally use server.listen() to bind a TCP socket for listening. The callback function uses information from the incoming HTTP request (req) to send an appropriate response (res).
What’s remarkable about this example isn’t what it does, but rather what it doesn’t do. A typical web server would take care of lots of little jobs that this code doesn’t touch. Here are some examples:
The Express framework helps with these and myriad other tasks.