Reputation: 3266
I am currently running a Node.js repl
to evaluate code, using the regular commend repl.start const repl = Repl.start({ prompt });
This starts a the console as expected.
I wish to send code to the server from my browser in order to evaluate it and display it back in the browser, however didn't find any documentation to do so. Is this possible at all?
Upvotes: 6
Views: 1562
Reputation: 3198
Is this possible at all?
Yes, and it's also very dangerous, because a script could require some filesystem utility and start copying, deleting, or reading files that the browser should not be able to reach through a Web server.
That being said, assuming you know what you are asking, this is an example of how you could achieve something similar.
It's using sockets for simplicity, but you could use fetch to send all data at once and receive output results.
package.json
{
"name": "browser-repl",
"main": "index.js",
"dependencies": {
"express": "^4.17.1",
"pocket.io": "^0.1.4"
}
}
index.html
<!doctype html>
<html>
<head>
<script src="/pocket.io/pocket.io.js"></script>
<script>
this.onload = () => {
const socket = io();
socket.on('eval', result => {
repl.value += result;
});
sender.addEventListener('click', () => {
const {value} = repl;
repl.value = '';
socket.emit('eval', value.trim() + '\n');
});
};
</script>
</head>
<body>
<textarea id="repl"></textarea>
<button id="sender">evaluate</button>
</body>
</html>
index.js
const repl = require('repl');
const app = require('express')();
const http = require('http').Server(app);
const io = require('pocket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
let connected = true;
const r = repl.start({
writer(data) {
if (connected)
socket.emit('eval', data);
return data;
}
});
socket.on('eval', function (input) {
r.input.emit('data', input);
});
socket.on('disconnect', function () {
connected = false;
r.input.emit('data', '.exit\n');
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
You can npm i
in that folder containing the 3 files, then run node .
or node index.js
and go to http://localhost:3000/ after.
Feel free to type in the textarea 1+1
or anything else you like and then press evaluate
.
This is obviously a hint on how to start, so that your question should be somehow answered.
Regards
Upvotes: 5