Using NPX command for shell script shebang / interpreter - node.js

I'd like to run a command line script using the coffee executable, but I'd like to call that executable through npx.
Something like #!/usr/bin/env npx coffee does not work, because only one argument is supported via env.
So, is there a way to run an npx executable via env?

Here is a solution using ts-node.
Any single OS, ts-node installed globally
#!/usr/bin/env ts-node
// TypeScript code
You probably also need to install #swc/core and #swc/cli globally unless you do further configuration or tweaking (see the notes at the end). If you have any issues with those, be sure to install the latest versions.
macOS, ts-node not installed globally
#!/usr/bin/env npx ts-node
// TypeScript code
Whether this always works in macOS is unknown. There could be some magic with node installing a shell command shim (thanks to #DaMaxContext for commenting about this).
This doesn't work in Linux because Linux distros treat all the characters after env as the command, instead of considering spaces as delimiting separate arguments. Or it doesn't work in Linux if the node command shim isn't present (not confirmed that's how it works, but in any case, in my testing, it doesn't work in Linux Docker containers).
This means that npx ts-node will be treated as a single executable name that has a space in it, which obviously won't work, as that's not an executable.
See the notes at the bottom about npx slowness.
Cross-platform with ts-node not installed globally in macOS, and some setup in linux
Creating a shebang that will work in both macOS and Linux (or macOS using Docker running a Linux image), without having to globally install ts-node and other dependencies in macOS, can be accomplished if one is willing to do a little bit of setup on the Linux/Docker side. Obviously, Linux must have node installed.
Use the #!/usr/bin/env npx ts-node shebang. We just have to fool Linux into thinking that npx ts-node with the space is actually a valid executable name.
Build a named Docker image that has the required dependencies globally installed and a symbolic link making npx ts-node resolve to just ts-node.
Here is an example all-in-one command line on macOS that will both build this image and run it:
docker buildx build -t node-ts - << EOF
FROM node:16-alpine
RUN \
npm install -g #swc/cli #swc/core ts-node \
&& ln -s /usr/local/bin/ts-node '/usr/local/bin/npx ts-node'
ENV SWC_BINARY_PATH=/usr/local/lib/node_modules/#swc/core/binding
WORKDIR /app
EOF
docker run -it --rm \
-v "$(pwd):/app" \
node-ts \
sh
Note that for this example script to work, the above line containing EOF must not have any other characters on the line, before or after it, including spaces.
Inside of the running container, all .ts scripts that have been made executable chmod +x script.ts will be executable simply by running them from the command line, e.g., ./test-script.ts. You can replace the above sh with the name of the script, as well (but be sure to precede it with ./ so Docker knows to run it as an executable instead of pass it as an argument to node).
Additional Thoughts & Considerations
There are other ways to achieve the desired functionality.
The docker run command can mount files into the image, including mounting executables in various directories. Some creative use of this could avoid needing to install anything or build a docker image first.
The install commands could be part of the docker run instead of pre-building an image, but then would be performed on each execution, taking much longer.
The PATH could be modified in macOS, linux, and in the docker build to add the folder containing ts-node's bin.js from any ts-node dist directory, then a shebang of #!/usr/bin/env bin.js should theoretically work (and can try bin-esm.js to avoid needing SWC, though this enters experimental node territory and may not be suitable for production scripts). This works in macOS, and in Docker outside of an npm project, and in Docker inside of an npm project configured to use TS & swc by passing the --skipProject flag to ts-node or setting environment variable TS_NODE_SKIP_PROJECT=true. A working test command line example: docker run -it --rm -v "$(pwd):/app" -e TS_NODE_SKIP_PROJECT=true -w /app --entrypoint sh node:16-alpine -c 'PATH="$PATH:/app/node_modules/ts-node/dist" ./test.ts'.
Any named executable that can be found in the PATH and run via direct command can be a shebang (using #!/usr/bin/env executable). It can be a shell script, a binary file, anything. A shell script can easily be put at a known location, added to the PATH, and then call whatever you like. It could be multi-statement, compiling the file to .js, then running that. Whatever your needs are.
In some special cases you might want to simply use node as your shebang executable, setting node options through environment variables to force ts-node as your loader. See ts-node Recipes:Other for more info on this.
Notes:
The SWC_BINARY_PATH environment variable ensures that ts-node can find the architecture-specific swc compiler (to avoid error "Bindings not found"). If you're running on only one architecture, you won't need it. Or, if you are mounting node_modules that have these #swc packages already installed for the correct architecture, you won't need it.
It is possible to install node_modules binaries for multiple architectures. The way to do this varies between the different package managers. For example, yarn 3 lets you define which binaries to install all at once in .yarnrc.yml. There are other options for npm and possible yarn 1 (and 2?) using environment variables.
ts-node does offer options for running without swc (though this is slower). You could try shebangs with ts-node-esm instead of ts-node. Look at all the symlinks in the /usr/local/bin folder or consult ts-node documentation for more information. If ts-node
It is possible to run .ts files directly using node and setting node options in environment variables. node --loader=ts-node does work, in recent versions (16+?). The experimental mode warnings can be suppressed.
There are some crazy ways to trick the shell to run JavaScript instead of a unix shell. Check out this answer that uses a normal sh shebang, but a clever shell statement to transfer execution over to node, that is basically ignored by JavaScript. This isn't great as it requires extra lines of trickery, but could help some people. Other answers on the page are also instructive and it's worth reviewing to get the full picture.
Some of the complexity here might go away if running .ts files outside of an npm project. In my own testing in Docker, the context was always in a project having its own tsconfig.json and swc installed, so with a different setup you might have different results. It proved to be difficult to get ts-node to ignore npm project context found with the executed .ts file.
The difference between ESM and CommonJS module handling has not been explained here. This is a complicated topic and beyond the scope of this answer.
Suffice it to say that if you can figure out how to run your scripts from the command line in the form executable [options] [file], then you should be able to figure out how to run ./[file] with an appropriate shebang, by mixing and matching all the ideas presented here. You don't have to use ts-node. You can directly use node, swc, tsc itself (by first compiling and then running any .js file or set of .js files in the found context), or any utility or tool that is able to compile or run TypeScript.
Note that using npx is significantly slower than running ts-node directly, because it may need to download the ts-node package, and dependencies, every time it runs.
Some various random tips on possible strategies for SWC architecture support:
https://socket.dev/npm/package/#rnw-community/nestjs-webpack-swc
https://github.com/yarnpkg/yarn/issues/2221

Related

How to run NodeJS CLI tools without having to type npx

TL;DR
I cannot execute commands such as tsc unless I include npx before it (e.g npx tsc). How can I fix this?
The title is a bad explanation of the problem I have.
Say I have installed an npm package with a CLI with it (typescript in this example). And the CLI is used like
tsc <filename> or just tsc. But whenever I try to do it like that, I get an error like
'tsc' is not recognized as an internal or external command,
operable program or batch file.
But... when I do
npx tsc
then it works!
So whats the problem?
The problem with doing npx tsc is because
npx is slow at executing commands
its annoying having to type npx and the front of every command.
And the thing is, this was originally not a problem with WSL.
Why dont you just use WSL?
I have always had problems with WSL (primarily permission issues due to security reasons) and so I uninstalled WSL and just used command prompt. I would have perferred using WSL but it was simply not an option.
Other Info:
I am using Windows command prompt.
I have installed the packages globally
So is there a way to just execute commands that way or is it Command prompts fault?
! this only works for Windows !
Ok, so I came across this post and thankfully, the first answer there was the solution!
Just add %USERPROFILE%\AppData\Roaming\npm to the path variable in system variables!
To access the system variables, press the Windows key, type Environment variables and click on Environment variables at the bottom of the window. The path variable can be found under User variables for (profile name).

Team City "minimal build agent" Docker image - "npm: not found" Linux issue?

First of all, I think this is more of a Linux issue as the problem seems to be on a linux-flavoured Docker container, but I'm happy to accept that I can do something to the team city config to overcome this.
I'm also not very experienced with Linux, Docker or node/npm, though I do have a lot of development experience and am very comfortable with command line interfaces in general.
Background
We currently have Team City set up as a build server, for building a variety of projects:
.Net Framework,
.Net Core
Angular CLI
A couple of simple websites which use node packages to generate HTML from Markdown.
The server is running as a Docker container using Docker for Windows on a Windows Server box, and this is working well.
We have one Windows 10 Build agent (a VM) which is also working fine, and builds all the .Net and .Net Core stuff fine.
The simple docs site stuff primarily uses the markdown-to-html node package, so its build steps simply get all the source .md files and compile to html with markdown-to-html, plus use some other npm packages for SASS compilation and minification of js etc. No actual node code as such, just some jQuery. In order to not tie up the other agent, and because this stuff can run happily on Linux, I want to have this running on a small docker image rather than a full VM build agent somewhere.
I previously successfully used a node.js team city agent docker image (either jacobpeddk/teamcity-agent-nodejs or omez/teamcity-agent-nodejs - can't recall) which did work for a time, though I had issues with being able to install some npm packages globally in build scripts, which meant I had to get a bash terminal into the container and run some manual npm commands. I also I think had to run apt-get install zip to get a zipping step to work. This worked fine for a while (weeks).
I added some extra JS stuff to one of these simple projects, and suddenly I was getting errors when trying to build. I (perhaps stupidly) decided that this was probably due to the container having older versions of node and/or npm etc, so I attempted to update this by getting a bash shell into the container, installing nvm and updating node.js & npm.
This ended up with a rather broken container (node errors), so I thought I'd instead start again, but actually start with the jetbrains/minimal-build-agent Docker image instead, with the aim of ending up with a nice bespoke image for our needs specifically (as I couldn't find a very up-to-date pre-existing one)
I've running a Bash shell directly on the build agent container by executing this on the host:
docker exec -it basicagent /bin/bash
then from there I've installed nvm, Python (required for node install step) and node:
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.2/install.sh | bash
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion
apt-get update
apt-get install python 3.6
nvm install v8.11.1 (matching version on my dev machine)
npm install -g markdown-folder-to-html (npm package I previously found I had to install globally)
apt-get install zip (just used for a build step to zip up artifacts)
If I now run (via the bash shell) npm -version I get back 5.6.
If I try to get a build to run that uses npm in a command line step, then I get this error in the build log:
/opt/buildagent/temp/agentTmp/custom_script2764770419520852926: npm: not found
I wondered if it was an issue with the user/path that the team city agent process is using vs. the one I'm using in Bash, so I added the following to the build script:
echo PATH = $PATH
echo user var = $USER
echo user via 'id':
id -u -n
the output of which is:
PATH = /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
user var =
user via id:
root
So it's running the agent as root, and doesn't appear to have node in the $PATH at all.
If I run the above directly from Bash however, I can see that I am root, but my $PATH is different:
PATH = /root/.nvm/versions/node/v8.11.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
root
So I'm now confused: I've re-started the container and this has had no effect - it seems that when I'm logged in as root manually I have a certain path set, but when the build agent service is running as root it's different.
I have no idea why this happens, but I've basically worked around the problem by adding:
export PATH=$PATH:/root/.nvm/versions/node/v8.11.1/bin
to the top of every build step that uses npm in a script. To my mind this seems a rather daft thing to have to do - considering this used to work without this, and the only real difference is possibly a slightly different flavour of linux container. AFAIK the original build agent container was based on the jetbrains minimal-build-agent one, so unless they've changed what they base that on it should be roughly the same...
I also had to change the compressor being used in a node-minify build step from gcc (google closure compiler) to babel-minify as the former was basically hanging indefinitely, but that is a separate problem (though also something that was fine and now isn't...)
Thanks to anyone who took the time to read... though I do wonder if one-day I'll exhaust my own research options, and finally go ask the internet and actually get someone respond - for some reason whenever I get to the point where I have to ask, it always seems no-one else has the answer either and I end up having to work it out myself. It's probably character-building though I suppose.. (this isn't just SO - I've found this be the case for over 15 years on various forums about various things...)

Jenkins build step fails when calling "npm" on mac-os-x Yosemite

Before I start, I want to say that I already checked these answers:
Jenkins build step fails on 'npm install <whatever>'
Jenkin's build failing on npm install
Now, I'm dealing with this issue for a while already and thus I tried a bunch of stuff.
Firstly, I installed node + npm via homebrew. A simple $ node -v and $ npm -v echoed the version v0.10.36 for node and v2.3.* for npm, which also means I HAVE THEM IN THE PATH and they work while called in the terminal.
Simply adding node -v; npm -v to the execute shell in Jenkins didn't do it. After a bit of tinkering I copied what $: which node yielded in the terminal to the above mentioned script, which now looked like this: /usr/local/bin/node and apparently that worked. The Jenkins build succeeded and 'node-v0.10.36' was proudly displayed in the console output.
When doing the same for 'npm' which happened to be /usr/local/bin/npm --version the computing gods weren't so merciful anymore. A big 'env: node: No such file or directory' error was thrown this time and the whole build failed.
The actual command that fails is
$ /bin/sh -xe /var/folders/wr/g_dl81tn5_x0t_yz3jw602cr0000gn/T/hudson8770480548136671253.sh and "surprisingly" when I run the same command in the terminal it succeeds.
I also uninstalled the homebrew node & npm versions and installed them afterwards via the package manager. Same results.
Ultimately I also did this: https://gist.github.com/DanHerbert/9520689, with no luck.
Notes:
I'm running Jenkins 1.613 and tried with 1.5**
I didn't create a "Jenkins" specific user but instead I'm using the admin. This happens to be the same user that Jenkins runs, since the who am i command inside the executable script yields the admin's user name.
sudo'ing doens't help
I'm also running the whole thing in a Virtual Environment - vagrant
I'm not running Jenkins as a deamon, as it's conflicting with xtools, but as a simple process
I also tried out jenkins-node plugin with various configs (can detail if needed)
Thanks a lot for your help, and let me know if you need any other info, screenshots, logs, etc.
I found my own solution. The problem was that the PATH although visible in shell was not exported for the Jenkins job, and so, the first workaround, as found here, was to export it in the actual script like so:
but this feels like a hack!
The right and elegant solution is to use Jenkins EnvInject Plugin and export the path in the added Properties content textarea on the configuration page, like so:
Manage Jenkins -> Configure System -> Global properties -> Environment variables

Getting SublimeText2 to compile Typescript

Really excited about using Typescript on the Mac however, even after a full day of troubleshooting, unable to get it to compile in SublimeText. Followed these directions (the first at the top) to install nodes and npm>
https://gist.github.com/isaacs/579814
Installed Typescript
sudo npm install -g typescript
Installed the syntax highlighting package for sublime
http://msopentech.com/blog/2012/10/01/sublime-text-vi-emacs-typescript-enabled/
Created a build file 'typescript.sublime-build as follows
{
"selector": "source.ts",
"cmd": ["tsc", "$file"],
"path": "/usr/local/bin",
"file_regex": "^(.+?) \\((\\d+),(\\d+)\\): (.+)$"
}
When I type $which node I get
/usr/local/bin/node
When I type $which tsc I get
/Users/<username>/local/bin/tsc
BUT, whenever I try to compile even the simplest .ts file in SublimeText the first effort message I get is
[Errno 2] No such file or directory
Can anyone suggest further troubleshooting steps?
I struggled with a little too. It seems the PATH is quite different when trying to run commands directly from the build system than the terminal, and this is a cause of problems.
What I did as a simple workaround was just set my command to run a Bash script, i.e. in the sublime.project file have the command as..
"cmd": ["./build.sh"]
.. and then in the build.sh script in my project folder simply run the compiler, i.e..
#! /bin/bash
tsc --target ES5 foo.ts
Obviously this assumes foo.ts pulls in all the other project files so they get compiled (or you could glob for the files on the command-line seeing as you're running a Bash command).
This might be a quick and simple solution for you.
You could do what my team mates do. Use Sublime Text for text editing with a grunt watch in the background compiling any files that change : https://github.com/basarat/grunt-ts

Node.js Cygwin not supported

I am trying to install node.js. I followed this tutorial and i am stuck in the middle.
When I write ./configure in my cygwin terminal it says "cygwin not supported". Please help me out
Thanks in advance.
Node in my experience runs fine in cygwin, what Node usually has EINVAL errors in seems to be MINTTY which is a terminal emulation 'skin' that is default to cygwin. I still am not sure why these EINVAL errors happen 100% but the following are the steps and tricks I use to get node working.
In my /cygwin/home/{username}/.bashrc I add node to path so cygwin can find it
export PATH=$PATH:"/cygdrive/c/Program Files/nodejs/"
If you run a 32 bit version of node:
export PATH=$PATH:"/cygdrive/c/Program Files (x86)/nodejs/"
Then to make npm run without windows to linux issues I launch cygwin in admin mode then run:
dos2unix '/cygdrive/c/Program Files/nodejs/npm'
At this point running files and most npm packages will run in MINTTY just fine, although every once and awhile you will run into EINVAL issues with certain npm packages as karma. Also you will not be able to run the interpreter directly in MINTTY, anytime I want to do these things I run:
cygstart /bin/bash
This will open a native cygwin bash.exe window, from here you run the interpreter or an any troubling package command that results in a EINVAL. It slightly sucks you have to do this but I rarely use this day to day, and I love MINTTY too much to not use it.
Also note that you can run any one line node code in MINTTY by just running something like:
node -e "console.log('hello node')"
As a simpler derivative of troy's answer for those just looking to install NPM packages:
Install Node.js with the Windows installer package.
Add it to the PATH with export PATH=$PATH:"/cygdrive/c/Program Files/nodejs/" (obviously replacing the path to Node.js's installation directory with where you installed it).
There's a current bug in the Windows version that can be fixed by running mkdir -p ~/AppData/Roaming/npm. This is a bug for all of Windows and not just Cygwin. At some point of the future, you won't have to do this anymore, but the command shouldn't have any negative side effects.
Test it. Eg, npm install pretty-diff -g.
In order to be able to run the newly installed software, you'll need to add the install locations to your PATH. You can find these with npm bin -g and npm bin (the -g flag is the "global" installation location).
Not really anything special that you have to do to get it to run in Cygwin (although I can't say if everything works).
Use Console2, it allows you to run create tabs of CLI shells. It seems running cygwin inside console2 allows me to use node REPL just fine. I have no idea why :P
Follow this guide to add cygwin to console2:
http://blog.msbbc.co.uk/2009/11/configuring-console-2-and-bash-with.html
With Bjørn's suggestion (using Console2) and Soyuka's alias (steps here), my node.js v0.10.13 and npm v1.3.2 are now working under Babun v1.02, a Cygwin distribution.
For windows, Just run bash.exe in cmd, so that you could have a bash work around with cmd console directly, which could support ALL NODE WORKING PERFECTLY.
C:\Users\郷>bash
郷#CHIGIX ~
$ node
>
I'm using this wrapper in /usr/local/bin/node (note no extension!)
#!/bin/sh
_cmd="$(cygpath -lw -- "$1" )"
shift
"/proc/cygdrive/C/Program Files/nodejs/node.exe" "$_cmd" "$#"
This is far from perfect, as Node do not understand Cygwin directory tree, but works relatively well with relative names.
From Windows, run Cygwin.bat (instead of Cygwin Terminal) then in that run node: see and reply on this answer on this effectively-same question asked 1.5 years later.
Grab and run the node.js Windows installer.
In the Cygwin prompt type node
See if it works.

Resources