Skip to content

Instantly share code, notes, and snippets.

@maman
Last active May 18, 2020 01:15
Show Gist options
  • Save maman/9595d367d5c79d81025f7ea43a422950 to your computer and use it in GitHub Desktop.
Save maman/9595d367d5c79d81025f7ea43a422950 to your computer and use it in GitHub Desktop.
Deno repl server
import { serve } from "https://deno.land/[email protected]/http/server.ts";
const s = serve({ port: 8000 });
console.log('Server online at http://localhost:8000');
for await (const req of s) {
switch(req.url) {
case '/run': {
const {headers, method} = req;
const contentType = headers.get('Content-Type');
if (method === 'POST' && contentType == 'application/javascript') {
const textDecoder = new TextDecoder();
const bodyEncoded = await Deno.readAll(req.body);
const body = textDecoder.decode(bodyEncoded);
const executor = Deno.run({
cmd: ['deno', 'eval', body],
stdout: 'piped',
stderr: 'piped',
});
const {code} = await executor.status();
let output;
let outputString;
if (code === 0) {
output = await executor.output();
} else {
output = await executor.stderrOutput();
}
outputString = textDecoder.decode(output);
const headers = new Headers();
headers.set('Content-Type', 'text/plain');
req.respond({status: 200, headers, body: outputString});
break;
} else {
req.respond({status: 500, body: 'Not available'});
break;
}
}
case '/':
default:
// TODO: editor
req.respond({body: 'Editor'});
break;
}
}
@maman
Copy link
Author

maman commented May 16, 2020

$ deno run --allow-net --allow-run repl-server.ts
# feed it with deno source code
$ curl --location --request POST 'localhost:8000/run' \
> --header 'Content-Type: application/javascript' \
> --data-raw 'console.log('\''Hi deno!'\'');'
# and get the output:
Hi deno!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment