Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active July 17, 2022 09:07
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rauschma/834ba6e3d31c0fdc9a657cdeff3417d7 to your computer and use it in GitHub Desktop.
Save rauschma/834ba6e3d31c0fdc9a657cdeff3417d7 to your computer and use it in GitHub Desktop.

Creating standalone ESM-based Node.js scripts on Unix and Windows

Approach:

  1. The file starts with shell code.
  2. That code uses Node.js to execute the file in ESM mode, after it removes the initial non-JavaScript lines.
    • Node.js does not currently have CLI flags for achieving what we do in this step. Therefore, we have to pipe to the node executable.

When editing this file, we want to use the JavaScript mode of our IDE or editor. Therefore, we try to “hide” the shell code from JavaScript as much as possible.

Suggestions for improvements welcome!

#!/bin/sh
':' // ; tail --lines=+3 "$0" | node --input-type=module - $@ ; exit $?
// --lines=+3 removes 2 lines
import * as os from 'node:os';
console.log(os.homedir());
console.log(process.argv);
// Standalone ESM-based Node.js script on Unix
// Explanations: https://sambal.org/2014/02/passing-options-node-shebang-line/
:: /*
@echo off
more +5 %~f0 | node --input-type=module - %*
exit /b %errorlevel%
*/
import * as os from 'node:os';
console.log('HOME', os.homedir());
console.log(process.argv);
// Standalone ESM-based Node.js script on Unix
@sgourley
Copy link

Very nice! A couple of tiny mods to myscript.bat you might consider? Changing %0 to %~f0 in line 3 would allow invoking from the Windows command line using simply myscript rather than myscript.bat. Also changing 0 in line 4 to %errorlevel% would propagate any exit code to a parent process:

more +5 "%~f0" | node --input-type=module
exit /b %errorlevel%

@rauschma
Copy link
Author

@sgourley Excellent suggestions, thanks! I’ve changed myscript.bat accordingly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment