Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active July 17, 2022 09:07
Show Gist options
  • 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
@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