UNPKG

file-streamer

Version:

A TypeScript package for streaming data as files (Excel, CSV, JSON, Base64) and streaming files from file system through HTTP responses

49 lines 1.78 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.pipeFileFromPath = void 0; const fs_1 = require("fs"); const path_1 = require("path"); const utils_1 = require("../../utils"); const pipeFileFromPath = async (res, filePath, fileName, contentType) => { try { let fileStats; try { fileStats = (0, fs_1.statSync)(filePath); } catch (error) { throw new Error(`File not found: ${filePath}`); } if (!fileStats.isFile()) { throw new Error(`Path is not a file: ${filePath}`); } const fileExtension = (0, path_1.extname)(filePath); const mimeType = contentType || (0, utils_1.getContentTypeFromExtension)(fileExtension); let responseFileName; if (fileName) { responseFileName = fileName.includes('.') ? fileName : `${fileName}${fileExtension}`; } else { responseFileName = (0, path_1.basename)(filePath); } res.setHeader('Content-Type', mimeType); res.setHeader('Content-Disposition', `attachment; filename="${responseFileName}"`); res.setHeader('Content-Length', fileStats.size); const readStream = (0, fs_1.createReadStream)(filePath); readStream.on('error', (error) => { console.error('Error reading file:', error); if (!res.headersSent) { res.status(500).end('Error reading file'); } }); readStream.pipe(res); } catch (err) { console.error(err); if (!res.headersSent) { res.status(500).end('Internal server error'); } throw err; } }; exports.pipeFileFromPath = pipeFileFromPath; //# sourceMappingURL=stream.js.map