Last active
August 16, 2026 14:43
-
-
Save aquapi/8d204c2c2e10adf04ff8fecfe44b81e3 to your computer and use it in GitHub Desktop.
Simple file server
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
| // server.js | |
| const FILES = { | |
| 'minecraft-map': { | |
| path: './minecraft-map.zip' | |
| }, | |
| }; | |
| Bun.serve({ | |
| routes: { | |
| '/recieve/:id': async (req, server) => { | |
| const tag = `[id ${req.params.id}]`; | |
| console.log(tag, 'upload request from:', server.requestIP(req)); | |
| const fileInfo = FILES[req.params.id]; | |
| if (typeof fileInfo === 'undefined') { | |
| console.warn(tag, 'upload unknown file id'); | |
| return new Response(`unknown file: ${req.params.id}`, { | |
| status: 404 | |
| }); | |
| } | |
| console.log(tag, 'file size:', req.headers.get('content-length')); | |
| const interval = setInterval(() => { | |
| console.log(tag, 'uploading...'); | |
| }, 2000); | |
| try { | |
| await Bun.write(fileInfo.path, req.body); | |
| } catch (e) { | |
| console.error(tag, 'file upload error:', e); | |
| return new Response('file upload error', { | |
| status: 500 | |
| }); | |
| } finally { | |
| clearInterval(interval); | |
| } | |
| console.log(tag, 'file upload succeeded'); | |
| return new Response('file uploaded'); | |
| }, | |
| }, | |
| port: prompt('server port (default to 3000):') || '3000', | |
| hostname: '0.0.0.0', | |
| }); | |
| console.log('server started successfully!'); | |
| // client.js | |
| /** | |
| * @param {string} addr | |
| * @param {keyof typeof FILES} id | |
| * @param {string} path | |
| */ | |
| export const upload = async (addr, id, path) => { | |
| const interval = setInterval(() => { | |
| console.log('uploading', id); | |
| }, 2000); | |
| try { | |
| const response = await fetch(addr + '/recieve/' + id, { | |
| method: "POST", | |
| body: Bun.file(path) | |
| }); | |
| if (response.ok) { | |
| console.log('file upload succeeded!'); | |
| return; | |
| } | |
| if (response.status === 404) | |
| console.error('unknown file id:', id); | |
| console.error('status:', response.status); | |
| console.error('response:', response); | |
| } catch (e) { | |
| console.error('file upload failed:', e); | |
| } finally { | |
| clearInterval(interval); | |
| } | |
| process.exit(1); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment