wasm_exec_node.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Copyright 2021 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. "use strict";
  5. if (process.argv.length < 3) {
  6. console.error("usage: go_js_wasm_exec [wasm binary] [arguments]");
  7. process.exit(1);
  8. }
  9. globalThis.require = require;
  10. globalThis.fs = require("fs");
  11. globalThis.TextEncoder = require("util").TextEncoder;
  12. globalThis.TextDecoder = require("util").TextDecoder;
  13. globalThis.performance = {
  14. now() {
  15. const [sec, nsec] = process.hrtime();
  16. return sec * 1000 + nsec / 1000000;
  17. },
  18. };
  19. const crypto = require("crypto");
  20. globalThis.crypto = {
  21. getRandomValues(b) {
  22. crypto.randomFillSync(b);
  23. },
  24. };
  25. require("./wasm_exec");
  26. const go = new Go();
  27. go.argv = process.argv.slice(2);
  28. go.env = Object.assign({ TMPDIR: require("os").tmpdir() }, process.env);
  29. go.exit = process.exit;
  30. WebAssembly.instantiate(fs.readFileSync(process.argv[2]), go.importObject).then((result) => {
  31. process.on("exit", (code) => { // Node.js exits if no event handler is pending
  32. if (code === 0 && !go.exited) {
  33. // deadlock, make Go print error and stack traces
  34. go._pendingEvent = { id: 0 };
  35. go._resume();
  36. }
  37. });
  38. return go.run(result.instance);
  39. }).catch((err) => {
  40. console.error(err);
  41. process.exit(1);
  42. });