Created
August 15, 2024 12:19
-
-
Save furaar/552441ecea11db1bf4e7f3423a9f4bc5 to your computer and use it in GitHub Desktop.
Quickly stream a file a over the network.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Stream.js | |
Descriptiopn: Quickly stream a file over the network | |
Dependency: npm i -g http | |
Run Syntax: stream.js <filename> | |
Author: @furaar | |
*/ | |
const http = require('http'); | |
const fs = require('fs'); | |
const path = require('path'); | |
// Get the filename from command-line arguments | |
const args = process.argv.slice(2); | |
if (args.length === 0) { | |
console.error('Please provide a filename as an argument'); | |
process.exit(1); | |
} | |
const filePath = path.join(__dirname, args[0]); // Use the provided filename | |
const server = http.createServer((req, res) => { | |
if (req.method === 'GET' && req.url === '/file') { | |
fs.stat(filePath, (err, stats) => { | |
if (err) { | |
console.error('File stat error:', err); | |
res.writeHead(500, { 'Content-Type': 'text/plain' }); | |
res.end('Internal Server Error'); | |
return; | |
} | |
res.writeHead(200, { | |
'Content-Type': 'application/octet-stream', | |
'Content-Length': stats.size, | |
'Content-Disposition': 'attachment; filename=' + path.basename(filePath) | |
}); | |
const readStream = fs.createReadStream(filePath); | |
// Handle read stream errors | |
readStream.on('error', (err) => { | |
console.error('File read error:', err); | |
res.end('Internal Server Error'); | |
}); | |
// Pipe the file stream to the response | |
readStream.pipe(res); | |
}); | |
} else { | |
res.writeHead(404, { 'Content-Type': 'text/plain' }); | |
res.end('Not Found'); | |
} | |
}); | |
const PORT = 3000; | |
server.listen(PORT, () => { | |
console.log(`Server is listening on port ${PORT}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment