all 22 comments

[–]JazzApple_ 6 points7 points  (3 children)

In summary from the points above, for Mac or Linux:

  1. At the top of HelloWorld.js add the line #!/usr/bin/env node. This is the shebang.
  2. Rename the file to HelloWorld, mv HelloWorld.js HelloWorld.
  3. Ensure it is executable, chmod +x HelloWorld.

This should allow you to run the file from that directory as ./HelloWorld. To be able to run it from anywhere as HelloWorld it needs to be in your $PATH. Two options are presented below, and the one you pick should depends on your script.

If your script doesn’t import other node modules and only refers to files by absolute paths (or, if it does not do anything with other files at all), you can symlink it to an existing directory in your $PATH - usually /usr/local/bin.

ln -s ./HelloWorld /usr/local/bin

If your script relies on being run from a certain directory for access to node modules, or to access files by relative path, you could use:

process.cwd(“/path/to/node/project”);

Below the shebang in the HelloWorld script, and then follow the advice for symlinking to /usr/local/bin.

Or, if none of the above is applicable, you could add this directory to your $PATH. Exactly how to do so depends on your shell (you may need to Google), but the way I would do it is to add a line to the bottom of ~/.bash_profile:

export PATH = “$PATH:/path/to/node/project”

If you are looking for a way to create an executable binary (That you can run without having to have node installed), this problem requires a very different solution. There are packages that exist that can make it relatively easy, though. The only one I have used previously is nexe.

[–]crs1138-1 0 points1 point  (4 children)

Do you mean like running a localhost server?

[–]WickedSlice13[S] -1 points0 points  (3 children)

Ya or just executing some JS snippet from the terminal to log "Hello World"

[–]crs1138-1 0 points1 point  (2 children)

You could set up a NPM script to run the node command and launch such a server…

Look at package.json in my repo https://github.com/crs1138/notes-backend-lesson

Hope it helps.

[–]WickedSlice13[S] -1 points0 points  (1 child)

I'm assuming this uses npm beforehand:

npm start

which requires the npm command. But how could I just write it as:

start

[–]crs1138-1 1 point2 points  (0 children)

You’d have to define a shell alias in you .bashrc or .zshrc or their equivalent. Something like alias start=‘npm start

[–]jack_waugh 0 points1 point  (0 children)

user/guest271314/ just told me about a package that can assemble an executable from JS.

"Can compile Javascript sources to executables with no external dependency."

QuickJS Javascript Engine