Where to store and how to reference a nodejs script?

Hi, newbie here. I’m learning Elixir Phoenix by porting a Node application to Elixir. There’s one Node script that I have not yet been able to fully port to Elixir so I’m trying to use it as a Node script within my Phoenix application.

I got it to work on my local machine.

When I deploy (on Fly.io) it doesn’t work. At first I put the file on /priv/static/nodefile.js but I saw that this file wasn’t present in the live build. After some further reading I realized that I needed to add it to a directory and add that directory to plug Plug.Static. I can now see the file, but I think I’m not referencing it properly.

{app, _} = System.cmd("node", ["./priv/static/dbdiagram/dbdiagram.js", url])

Where should I store Node scripts? How do I reference them?

The canonical way to do it is to put JavaScript files in /assets/js/your-file.js then import them in /assets/js/app.js. How you’re doing it work but then it won’t get bundled and you have to make sure to manually include it via <script> tag. The public URLs for static paths is everything after the priv/static, so in your case it would be <script src="/dbdiagram/dbdiagram.js"></script>. I suggest going the /assets/js/ route, though. You’re calling it a “nodescript”, though, so maybe it has a hard dependency on nodejs? In that case, is node installed on Fly? I’m a bit out of my element on this particularly point.

Thanks for the explanation.

Indeed, it should be run on the server instead of the user’s browser. So the script tag wouldn’t work in this case.

I believe I’ve got nodeJS installed on Fly. I’m getting “Module not found” when running this script which — in my limited testing and understanding — means that the .js file is not found.

I’m going to keep hacking away but any tips are helpful.

Ah, you want to be accessing it like this:

Path.join([:code.priv_dir(:my_app), "path", "to", "file"])

And make sure this is runtime code, ie, called within a function definition as the location of priv changes in prod.

Also, since this a file you are running with node, there is no need to give public browser access to it. Just store it somewhere in /priv outside of /static, like /priv/scripts or something.

EDIT: I wrote “access” when I meant the static/ directory.

2 Likes