Registry / http-networking / file-server

file-server

JSON →
library2.2.1jsnpmunverified

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.

npm install file-server
INSTALL
IMPORT
SIG · FILE-SERVER
F
file-server
http-networkingjavascriptv2.2.1
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

FileServer
✓ const FileServer = require('file-server');
✗ import FileServer from 'file-server';
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.

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.

const FileServer = require('file-server'); const http = require('http'); const path = require('path'); const fs = require('fs'); // Create a dummy file and directory for the example const tempDir = path.join(__dirname, 'temp-static'); const robotTxtPath = path.join(tempDir, 'robots.txt'); const imagesDir = path.join(tempDir, 'images'); if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir); if (!fs.existsSync(imagesDir)) fs.mkdirSync(imagesDir); fs.writeFileSync(robotTxtPath, 'User-agent: *\nDisallow: /private/', 'utf8'); fs.writeFileSync(path.join(imagesDir, 'test.png'), 'dummy image content', 'utf8'); // In a real scenario, this would be binary const fileServer = new FileServer((error, request, response) => { response.statusCode = error.code || 500; response.end(`Error: ${error.message || 'Internal Server Error'}`); }); const serveRobots = fileServer.serveFile(robotTxtPath, 'text/plain'); const serveImagesDirectory = fileServer.serveDirectory(imagesDir, { '.png': 'image/png', '.jpg': 'image/jpeg' }); const server = http.createServer((request, response) => { if (request.url === '/robots.txt') { serveRobots(request, response); } else if (request.url.startsWith('/images/')) { // The serveDirectory method automatically infers filename from request.url if not provided. serveImagesDirectory(request, response); } else { response.statusCode = 404; response.end('Not Found'); } }); const PORT = 8080; server.listen(PORT, () => { console.log(`File server listening on http://localhost:${PORT}`); console.log(`Try: http://localhost:${PORT}/robots.txt`); console.log(`Try: http://localhost:${PORT}/images/test.png`); }).on('close', () => { fileServer.close(() => { console.log('File server watchers closed.'); // Cleanup temporary files/directories after server closes fs.rmSync(tempDir, { recursive: true, force: true }); }); }); // To stop the server gracefully // process.on('SIGINT', () => { server.close(); });
Debug
Known issues
breakingVersion 2.0.0 removed support for Node.js versions older than 8. Ensure your Node.js environment is version 8 or higher.
fix
Upgrade your Node.js runtime to version 8.0.0 or later.
affects: >=2.0.0
gotchaError 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.
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.
affects: >=1.0.0
gotchaWhen 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.
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.
affects: >=1.0.0
gotchaFile 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.
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.
affects: >=1.0.0
Errors
Common errors & fixes
Error: Cannot find module 'file-server'
The `file-server` package has not been installed or is not resolvable in the current project context.
fix
Install the package using npm: `npm install file-server`.
TypeError: fileServer.serveFile is not a function
This error typically occurs if `FileServer` was not correctly imported or instantiated, leading to `fileServer` being undefined or not an instance of `FileServer`.
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.
Error: Not Found (or 404 in error callback) when serving a directory
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.
fix
Update the `mimeTypes` configuration for `serveDirectory` to include the specific file extension and its correct MIME type for the file being requested.
Error: The "path" argument must be of type string or an instance of Buffer or URL. Received undefined (when using serveDirectory without fileName argument)
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.
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);`.
Upgrade
Version history
2.2.1latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
4 hits · last 30 days
node
4
Resources
file-server — npm install file-server · libregistry