Beej's Bit Bucket
a day ago
- The tutorial is part of a series on building a WebSocket-based chat server, starting with a basic NodeJS webserver.
- Prerequisites include NodeJS installation and familiarity with JavaScript, especially asynchronous functions and callbacks.
- A webserver listens for HTTP connections, processes requests, and returns responses (e.g., files or 404 errors).
- The server is implemented the hard way (reinventing the wheel) for learning; real projects would use libraries like Connect or Serve Static.
- The general plan: listen for connections, determine requested file, check existence (including index.html for directories), determine MIME type, read file, and send response.
- NodeJS I/O functions come in synchronous (simpler) and asynchronous (more efficient for many requests) flavors; the tutorial uses async.
- Code skeleton uses `require('http')` to create a server, then extracts the request path and calls `getFilenameFromPath()` to locate the file.
- The `onGotFilename` callback handles errors (404, 500) or reads the file with `fs.readFile()`, determines MIME type, and sends the HTTP response.
- MIME type mapping is done via a simple function looking at file extensions; real-world use would rely on a library like `mime`.
- Security is critical: the server sanitizes the path to prevent directory traversal attacks (e.g., %2e%2e sequences) by ensuring the resolved path stays within the base directory.
- The complete server code is available on GitHub, and can be run with `node httpserver.js` on port 3490, serving files from the current directory.
- Testing can be done via browser or curl, which shows HTTP headers including the computed Content-Type.