{"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,"search_vec":"'2.2.1':25 '8':85 'access':105 'activ':69 'age':50 'api':32 'appear':59 'base':45,93 'block':110 'build':109 'cach':46,127 'cadenc':66 'callback':92 'callback-bas':91 'compress':53 'configur':47 'control':99 'creat':34 'current':21 'custom':35,112 'develop':71 'differenti':88 'directori':16,104,130 'error':94 'etag':44 'etag-bas':43 'explicit':98 'featur':41,70 'file':3,7,14,37,114,123 'file-serv':6,36 'focus':65 'fundament':108 'gzip':52,128 'handl':95 'handler':39 'http':2,13,129 'includ':89 'infer':54 'infrequ':60 'javascript':122 'key':87 'keyword':57 'last':74 'level':31 'librari':18 'like':42 'low':30 'low-level':29 'mainten':64 'maintenance-focus':63 'major':75 'max':49 'max-ag':48 'middlewar':120 'mime':101 'minimalist':12 'node.js':20,81 'offer':27,106 'older':83 'opinion':119 'packag':9,56 'provid':10 'rather':67,116 'remov':78 'serv':17,38,125 'server':4,8,115,124 'simpl':1 'solut':121 'stabl':23 'static':113,126 'suggest':61 'support':40,79 'system':96 'type':102 'updat':58,76 'v2.0.0':77 'version':24,82","created_at":"2026-04-19T13:35:08.392308+00:00","updated_at":"2026-04-19T13:35:08.392308+00:00","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","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/MauriceButler/file-server","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/file-server","openapi_spec":null,"status_page":null,"smithery":null,"categories":["http-networking","web-framework"],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-18","install_tag":null}}