| 70 | } |
| 71 | |
| 72 | function pipeFileToResponse(res, file, type) { |
| 73 | try { |
| 74 | // Validate file path - prevent directory traversal |
| 75 | const safeBasePath = path.join(__dirname, 'examples'); |
| 76 | const resolvedPath = path.resolve(path.join(safeBasePath, file)); |
| 77 | |
| 78 | // Ensure the resolved path is within intended directory |
| 79 | if (!resolvedPath.startsWith(safeBasePath)) { |
| 80 | res.writeHead(400); |
| 81 | res.end('Invalid file path'); |
| 82 | return; |
| 83 | } |
| 84 | |
| 85 | // Check if file exists |
| 86 | if (!fs.existsSync(resolvedPath)) { |
| 87 | res.writeHead(404); |
| 88 | res.end('File not found'); |
| 89 | return; |
| 90 | } |
| 91 | |
| 92 | if (type) { |
| 93 | res.writeHead(200, { |
| 94 | 'Content-Type': type, |
| 95 | }); |
| 96 | } else { |
| 97 | res.writeHead(200); |
| 98 | } |
| 99 | |
| 100 | const stream = fs.createReadStream(resolvedPath); |
| 101 | |
| 102 | stream.on('error', (err) => { |
| 103 | console.error('Error while reading file:', err.message); |
| 104 | if (!res.headersSent) { |
| 105 | res.writeHead(500, { 'Content-Type': 'text/plain' }); |
| 106 | } |
| 107 | res.end('File read error'); |
| 108 | }); |
| 109 | |
| 110 | stream.pipe(res); |
| 111 | } catch (err) { |
| 112 | console.error('Unexpected error:', err.message); |
| 113 | if (!res.headersSent) { |
| 114 | res.writeHead(500, { 'Content-Type': 'text/plain' }); |
| 115 | } |
| 116 | res.end('Internal server error'); |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | dirs = listDirs(__dirname); |
| 121 | |