UNPKG

als-send-file

Version:

file serving with advanced options for caching, headers, and error handling, compatible with Express middleware.

62 lines (55 loc) 2.59 kB
const { describe, it, before, after, beforeEach } = require('node:test'); const assert = require('node:assert'); const http = require('http'); const port = 22222; const baseUrl = `http://localhost:${port}/`; const mwFileHandler = require('../lib/mw'); const httpErrHandler = (res, code, msg) => { res.writeHead(code); res.end(msg); }; const { join } = require('path'); const root = join(__dirname, '..'); const { writeFileSync, unlinkSync } = require('node:fs'); const mw = mwFileHandler(root, httpErrHandler) const server = http.createServer((req, res) => mw(req, res, async () => { const { search, pathname } = new URL(req.url, 'http://some.com'); const options = {}; search.replace('?', '').split('&').forEach(val => { let [k, v] = val.split('='); if (v === 'true') v = true if (k) options[k] = v; }); res.sendFile(pathname, options) })); async function request(url, headers = {}, method = 'GET') { const response = await fetch(`${baseUrl}${url}`, { method, headers }); const text = await response.text(); return [response.status, text, response.headers, response]; } describe('fileHandler Tests', () => { const filename = 'test-file.txt' const testFilePath = join(root, filename); before(async () => { await new Promise(r => setTimeout(r, 1000)) writeFileSync(testFilePath, 'Hello from test-file.txt'); server.listen(port, () => { console.log(`Server running on http://localhost:${port}`); }); }); after(() => { unlinkSync(testFilePath); server.close(); }); it('should return 404 if file not found', async () => { const [status, text] = await request('nonexistent-file.txt'); assert.strictEqual(status, 404); assert.strictEqual(text, 'File nonexistent-file.txt not found'); }); it('should serve a file successfully with combined default and request-specific options', async () => { const [status, text, headers] = await request(filename + '?download=true&charset=utf-8'); assert.strictEqual(status, 200); assert.strictEqual(text, 'Hello from test-file.txt'); assert.strictEqual(headers.get('content-disposition'), 'attachment; filename="test-file.txt"'); assert.strictEqual(headers.get('content-type'), 'text/plain; charset=utf-8'); }); it('should respect no-cache directive when specified', async () => { const [status, , headers] = await request(filename + '?noCache=true'); assert.strictEqual(headers.get('cache-control'), 'no-cache'); }); });