File size: 2,129 Bytes
7319adc
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
{
  "id": "4a6f47d3-8284-4e71-b794-d6354e883e6d",
  "title": "Untitled",
  "content": "// server.js\nimport express from 'express';\nimport axios from 'axios';\nimport fs from 'fs';\nimport path from 'path';\nimport mime from 'mime-types';\nimport { pipeline } from 'stream/promises';\n\nconst app = express();\nconst PORT = 3000;\nconst CACHE_DIR = './cache';\n\nif (!fs.existsSync(CACHE_DIR)) {\n  fs.mkdirSync(CACHE_DIR);\n}\n\n\n// Stream & cache an toàn\napp.get('/stream/:filename', async (req, res) => {\n  const { filename } = req.params;\n  const cachedPath = path.join(CACHE_DIR, filename);\n  const tempPath = cachedPath + '.part';\n  const mimeType = mime.lookup(filename) || 'application/octet-stream';\n\n  if (fs.existsSync(cachedPath)) {\n    const stat = fs.statSync(cachedPath);\n    res.writeHead(200, {\n      'Content-Type': mimeType,\n      'Content-Disposition': `inline; filename=\"${filename}\"`,\n      'Content-Length': stat.size,\n      'Accept-Ranges': 'bytes',\n    });\n    fs.createReadStream(cachedPath).pipe(res);\n    return;\n  }\n\n  const HF_URL = `https://huggingface.co/datasets/TwanAPI/DataTwan/resolve/main/${encodeURIComponent(filename)}`;\n\n  try {\n    const response = await axios.get(HF_URL, {\n      responseType: 'stream',\n      headers: { 'User-Agent': 'Node.js Server' },\n    });\n\n    const writer = fs.createWriteStream(tempPath);\n    await pipeline(response.data, writer);\n    fs.renameSync(tempPath, cachedPath);\n\n    const stat = fs.statSync(cachedPath);\n    res.writeHead(200, {\n      'Content-Type': mimeType,\n      'Content-Disposition': `inline; filename=\"${filename}\"`,\n      'Content-Length': stat.size,\n      'Accept-Ranges': 'bytes',\n    });\n    fs.createReadStream(cachedPath).pipe(res);\n  } catch (err) {\n    console.error('❌ Lỗi khi stream:', err.message);\n    res.status(500).send('Không thể stream file từ Hugging Face.');\n  }\n});\n\napp.listen(PORT, () => {\n  console.log(`✅ Server đang chạy tại http://localhost:${PORT}`);\n});",
  "language": "javascript",
  "createdAt": 1762782323743,
  "updatedAt": 1762782323743
}