Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
6 lines (6 loc) · 1.94 KB
/
Copy pathserver.js
File metadata and controls
6 lines (6 loc) · 1.94 KB
1
2
3
4
5
6
const http=require('node:http');const fs=require('node:fs');const path=require('node:path');const {URL}=require('node:url');
const PORT=Number(process.env.PORT||3002),PUBLIC=path.join(__dirname,'public');
function send(res,status,body,type='application/json'){res.writeHead(status,{'content-type':`${type}; charset=utf-8`,'cache-control':'no-store'});res.end(type==='application/json'?JSON.stringify(body):body)}
async function image(res,u){const prompt=(u.searchParams.get('prompt')||'').trim();if(!prompt)return send(res,400,{error:'Add a prompt first.'});const width=Math.min(Math.max(Number(u.searchParams.get('width'))||1024,256),1536);const height=Math.min(Math.max(Number(u.searchParams.get('height'))||1024,256),1536);const target=`https://image.pollinations.ai/prompt/${encodeURIComponent(prompt)}?width=${width}&height=${height}&nologo=true`;try{const r=await fetch(target,{headers:{'user-agent':'Pollinations Image Studio/1.0'}});if(!r.ok)throw Error(`Pollinations returned HTTP ${r.status}`);const type=r.headers.get('content-type')||'image/jpeg';res.writeHead(200,{'content-type':type,'cache-control':'public, max-age=3600'});r.body.pipeTo(new WritableStream({write(chunk){res.write(Buffer.from(chunk))},close(){res.end()},abort(){res.destroy()}}))}catch(e){send(res,502,{error:e.message})}}
function staticFile(res,p){const file=path.normalize(path.join(PUBLIC,p==='/'?'/index.html':p));if(!file.startsWith(PUBLIC)||!fs.existsSync(file))return send(res,404,{error:'Not found'});send(res,200,fs.readFileSync(file),{'.html':'text/html','.css':'text/css','.js':'text/javascript'}[path.extname(file)]||'application/octet-stream')}
http.createServer(async(req,res)=>{const u=new URL(req.url,`http://${req.headers.host}`);if(u.pathname==='/api/image')return image(res,u);if(u.pathname==='/api/health')return send(res,200,{ok:true,service:'pollinations-image-studio'});staticFile(res,u.pathname)}).listen(PORT,()=>console.log(`Pollinations Image Studio: http://localhost:${PORT}`));