How to export functions from a node server and import them into a client?

In my client (index.html), which is not a module, I have this:

async function loadTheThings() {
  alert("loading...");
  let mod = await import("/index.mjs");
  alert("done!");
}
loadTheThings();

and in the server (index.mjs), which is a module because of the .mjs extension:

export function foo() {
  alert("hello world!");
}

I can’t seem to import anything though.

Node.js uses require() for imports and module.exports for exports. You can do import the functions like so:

// index.js (there's no need to put .mjs)
// ...
module.exports = { foo };
// index.html
// ...
function loadTheThings() {
    alert('loading...');
    let mod = require('/index.js');
    alert('done!');
}
loadTheThings();
1 Like

Hmm, after a bit more testing, it seems broken again.
index.js:

function foo() {
  alert("hello world!");
}

module.exports = { foo };

index.html:

alert("loading...");
let mod = require("/index.js");
alert("done!");

It says “loading…” but never gets to “done!”
I also tried putting those index.html lines in a setTimeout of 3000 to give it time to export, but that didn’t help.

require is a built-in function for NodeJS, it doesn’t exist in client side JavaScript. Could you provide a link (not a join link) to the repl you’re having difficulties with, it’d provide a little more context to your question and help others help you.

Oh, I thought require was vanilla JS

https://replit.com/@wooga123/spire-tcg

That’s what I suspected, it isn’t. Vanilla JS does have it’s own version of modules and imports which you can read about on MDN.

Yeah line 182 of index.html won’t work. The things you’ve required into your index.js file are built-in to NodeJS, not Vanilla JS.

1 Like

This isn’t working…

      <script type="module">
        alert("loading...");
        import * as mod from "/index.js";
        alert("done!");
...

And this doesn’t work either:

      <script>
        alert("loading...");
        let mod = import("/index.js");
        alert("done!");
...

That’s because 1) index.js is not hosted, so you’ll get a 404 if you try to import it, 2) you’re not using import correctly, it’s not the same as Python imports nor is it a function, and you can only use import inside a script with type="module", you would have to do import { someVar, someFunc } from "index.js"; or import someDefault from "index.js";, 3) your index.js file is NodeJS, for all intents and purposes, this is an entirely different language to vanilla JavaScript and importing it will only cause errors.

What are you trying to do, with a better idea of what you want I’d be able to help you more.

1 Like

My goal is to have data for a large amount of cards which is available to both the server and client; essentially, a large object with integers, strings, and functions. The data goes like this:

const CARD_DATA = {
  "Strike": ["Strike", "strike", 1, "Attack", { dmg: 6 }, "Deal !D! damage", function(s, d) {
    d.opp = deal(d.opp, "a", s.dmg);
    return d;
  }],
  "Defend": ["Defend", "defend", 1, "Skill", { blk: 5 }, "Gain !B! Block", function(s, d) {
    d.you = apply(d.you, "Block", s.blk);
    return d;
  }],
  "Bash": ["Bash", "bash", 2, "Attack", { mgc: 2, dmg: 12 }, "Deal !D! damage and apply !M! Vulnerable", function(s, d) {
    d.opp = deal(d.opp, "a", s.dmg);
    d.opp = apply(d.opp, "Vulnerable", s.mgc);
    return d;
  }]
}

I tried using type=module but it caused the script to not run at all.

1 Like

Then you can either hardcode it into the client, use WebSockets or set up an API. I would recommend one of the latter two.

To set up an API, in the server add something like this:

app.get("/api/cards", function(req, res) {
  res.type("json");
  res.send(CARD_DATA);
});

Then on the client side:

const CARD_DATA = await fetch("/api/cards").then((res) => res.json());

I haven’t tested that client side script, I’m not 100% sure about the way I used await, if that gives you an error, let me know.

This will allow you to send JSON data about each card to the client side, you could also just use Socket.IO to do this. If the client needed to respond on done way, it’d probably be best to use Socket.IO.

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.