Files
drawlogo/_design-test/serve.js
T

45 lines
2.1 KiB
JavaScript

// 临时静态服务器(仅用于本机预览 _design-test 产物)
// 用法: node _design-test/serve.js [port]
const http = require('http');
const fs = require('fs');
const path = require('path');
const ROOT = path.resolve(__dirname, '..');
const PORT = Number(process.argv[2] || 55501);
const MIME = {
'.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.woff2': 'font/woff2'
};
http.createServer((req, res) => {
// 供浏览器栅格化后回传 PNG 落盘(仅允许写入 _design-test/logo/ 下)
if (req.method === 'POST' && req.url.indexOf('/__save') === 0) {
const rel = decodeURIComponent((req.url.split('path=')[1] || ''));
const base = path.join(ROOT, '_design-test', 'logo');
const dest = path.join(base, rel);
if (!dest.startsWith(base)) { res.writeHead(403).end('forbidden'); return; }
const chunks = [];
req.on('data', c => chunks.push(c));
req.on('end', () => {
fs.mkdirSync(path.dirname(dest), { recursive: true });
fs.writeFileSync(dest, Buffer.concat(chunks));
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('ok ' + rel + ' ' + Buffer.concat(chunks).length + 'B');
});
return;
}
let p = decodeURIComponent(req.url.split('?')[0]);
if (p === '/') p = '/_design-test/zhenfang-logo-picker.html';
let file = path.join(ROOT, p);
if (!fs.existsSync(file) && fs.existsSync(path.join(ROOT, '_design-test', p))) {
file = path.join(ROOT, '_design-test', p); // 允许直接用 /xxx.html 访问 _design-test 下的产物
}
if (!file.startsWith(ROOT)) { res.writeHead(403).end('forbidden'); return; }
fs.readFile(file, (err, buf) => {
if (err) { res.writeHead(404).end('not found: ' + p); return; }
res.writeHead(200, { 'Content-Type': MIME[path.extname(file).toLowerCase()] || 'application/octet-stream' });
res.end(buf);
});
}).listen(PORT, () => console.log('serving ' + ROOT + ' at http://localhost:' + PORT + '/'));