{"id":10887,"library":"file-server","title":"Simple HTTP File Server","description":"The `file-server` package provides a minimalistic HTTP file and directory serving library for Node.js, currently at stable version 2.2.1. It offers a low-level API to create custom file-serving handlers, supporting features like ETag-based caching, configurable `max-age`, and GZIP compression (inferred from package keywords). Updates appear infrequent, suggesting a maintenance-focused cadence rather than active feature development, with the last major update (v2.0.0) removing support for Node.js versions older than 8. Its key differentiators include a callback-based error handling system and explicit control over MIME types and directory access, offering a fundamental building block for custom static file servers rather than an opinionated middleware solution.","status":"maintenance","version":"2.2.1","language":"javascript","source_language":"en","source_url":"https://github.com/MauriceButler/file-server","tags":["javascript","file","server","serve","static","cache","gzip","http","directory"],"install":[{"cmd":"npm install file-server","lang":"bash","label":"npm"},{"cmd":"yarn add file-server","lang":"bash","label":"yarn"},{"cmd":"pnpm add file-server","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"This package is primarily designed for CommonJS `require()` syntax. While modern Node.js supports ESM `import` statements, direct default imports of CJS modules can behave differently. For ESM contexts, consider dynamic `import('file-server')` or ensure your build system correctly handles CJS interop.","wrong":"import FileServer from 'file-server';","symbol":"FileServer","correct":"const FileServer = require('file-server');"}],"quickstart":{"code":"const FileServer = require('file-server');\nconst http = require('http');\nconst path = require('path');\nconst fs = require('fs');\n\n// Create a dummy file and directory for the example\nconst tempDir = path.join(__dirname, 'temp-static');\nconst robotTxtPath = path.join(tempDir, 'robots.txt');\nconst imagesDir = path.join(tempDir, 'images');\n\nif (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir);\nif (!fs.existsSync(imagesDir)) fs.mkdirSync(imagesDir);\nfs.writeFileSync(robotTxtPath, 'User-agent: *\\nDisallow: /private/', 'utf8');\nfs.writeFileSync(path.join(imagesDir, 'test.png'), 'dummy image content', 'utf8'); // In a real scenario, this would be binary\n\nconst fileServer = new FileServer((error, request, response) => {\n    response.statusCode = error.code || 500;\n    response.end(`Error: ${error.message || 'Internal Server Error'}`);\n});\n\nconst serveRobots = fileServer.serveFile(robotTxtPath, 'text/plain');\nconst serveImagesDirectory = fileServer.serveDirectory(imagesDir, {\n    '.png': 'image/png',\n    '.jpg': 'image/jpeg'\n});\n\nconst server = http.createServer((request, response) => {\n    if (request.url === '/robots.txt') {\n        serveRobots(request, response);\n    } else if (request.url.startsWith('/images/')) {\n        // The serveDirectory method automatically infers filename from request.url if not provided.\n        serveImagesDirectory(request, response);\n    } else {\n        response.statusCode = 404;\n        response.end('Not Found');\n    }\n});\n\nconst PORT = 8080;\nserver.listen(PORT, () => {\n    console.log(`File server listening on http://localhost:${PORT}`);\n    console.log(`Try: http://localhost:${PORT}/robots.txt`);\n    console.log(`Try: http://localhost:${PORT}/images/test.png`);\n}).on('close', () => {\n    fileServer.close(() => {\n        console.log('File server watchers closed.');\n        // Cleanup temporary files/directories after server closes\n        fs.rmSync(tempDir, { recursive: true, force: true });\n    });\n});\n\n// To stop the server gracefully\n// process.on('SIGINT', () => { server.close(); });","lang":"javascript","description":"This quickstart demonstrates how to instantiate `FileServer`, create handlers for a specific file and a directory, and integrate them with a basic Node.js HTTP server. It also shows how to gracefully close the file watchers."},"warnings":[{"fix":"Upgrade your Node.js runtime to version 8.0.0 or later.","message":"Version 2.0.0 removed support for Node.js versions older than 8. Ensure your Node.js environment is version 8 or higher.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"All error logic must be implemented within the `errorCallback` provided to the `FileServer` constructor. Wrap `file-server` handlers in Promise-based functions if you need async/await error handling upstream.","message":"Error handling is exclusively callback-based. Modern Node.js applications often use Promises or async/await, which are not directly supported for error interception within `file-server`'s API.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure that the `mimeTypes` object passed to `serveDirectory` includes all desired file extensions and their corresponding MIME types. Implement a fallback or custom logic in your main HTTP handler for unlisted types if needed.","message":"When using `fileServer.serveDirectory`, the `mimeTypes` argument strictly defines which file extensions are allowed. Requesting a file with an extension not specified in this object will result in a 404 error, even if the file exists.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Listen for the HTTP server's 'close' event (or a similar shutdown signal in your application) and invoke `fileServer.close(callback)` to ensure all underlying file watchers are properly released.","message":"File watchers opened by `file-server` are automatically closed on process exit. However, in scenarios like testing or frequent server restarts within a long-running process, you must manually call `fileServer.close()` to release file handles and prevent resource leaks.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Install the package using npm: `npm install file-server`.","cause":"The `file-server` package has not been installed or is not resolvable in the current project context.","error":"Error: Cannot find module 'file-server'"},{"fix":"Verify that `const FileServer = require('file-server');` is correctly used and `const fileServer = new FileServer((error, req, res) => {...});` is called before attempting to use its methods.","cause":"This error typically occurs if `FileServer` was not correctly imported or instantiated, leading to `fileServer` being undefined or not an instance of `FileServer`.","error":"TypeError: fileServer.serveFile is not a function"},{"fix":"Update the `mimeTypes` configuration for `serveDirectory` to include the specific file extension and its correct MIME type for the file being requested.","cause":"When using `fileServer.serveDirectory`, a 404 error is returned if a requested file's extension is not explicitly listed in the `mimeTypes` object provided to the `serveDirectory` method.","error":"Error: Not Found (or 404 in error callback) when serving a directory"},{"fix":"Ensure that `request.url` is properly populated when passing the handler directly to `http.createServer` or explicitly pass the `filename` argument to the handler: `serveDirectoryHandler(request, response, request.url);`.","cause":"If `fileServer.serveDirectory(root, mimeTypes)` is called without a `fileName` argument in its returned handler, it expects `request.url` to provide the path. If `request.url` is `undefined` or invalid, this error can occur.","error":"Error: The \"path\" argument must be of type string or an instance of Buffer or URL. Received undefined (when using serveDirectory without fileName argument)"}],"ecosystem":"npm"}