Skip to content

Instantly share code, notes, and snippets.

@jinjor
Last active December 31, 2019 09:53
Show Gist options
  • Save jinjor/1c87def1f75280aa957fa92e2405fb47 to your computer and use it in GitHub Desktop.
Save jinjor/1c87def1f75280aa957fa92e2405fb47 to your computer and use it in GitHub Desktop.
RPC between Browser and Node.js
async function exec(name, ...args) {
const res = await fetch(`/rpc/${name}`, {
method: "POST",
headers: {
"content-type": "application/json"
},
body: JSON.stringify(args)
});
const json = await res.json();
return json;
}
const express = require("express");
module.exports.start = function(options) {
const { port, public, funcs } = options;
const functions = new Map();
for (const name in funcs) {
functions.set(name, funcs[name]);
}
const app = express();
app.use(express.static(public));
app.use(express.json());
app.post("/rpc/:name", (req, res) => {
const funcName = req.params.name;
if (functions.has(funcName)) {
(async () => {
try {
const args = req.body;
const ret = await functions.get(funcName).apply(null, args);
res.send(ret);
} catch (e) {
console.log(e);
res.status(500).send({ message: e.message });
}
})();
} else {
res.status(404).send();
}
});
return new Promise((resolve, reject) => {
const server = app.listen(port, e => {
if (e) {
reject(e);
} else {
resolve(server);
}
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment