Skip to content

Instantly share code, notes, and snippets.

@christian-schulze
Forked from rauschma/README.md
Created July 12, 2022 02:04
Show Gist options
  • Save christian-schulze/4b95da46cc6f209bd2187f816896cb59 to your computer and use it in GitHub Desktop.
Save christian-schulze/4b95da46cc6f209bd2187f816896cb59 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());
// Standalone ESM-based Node.js script on Unix
// Explanations: https://sambal.org/2014/02/passing-options-node-shebang-line/
:: /*
@echo off
more +5 %0 | node --input-type=module
exit /b 0
*/
import * as os from 'node:os';
console.log('HOME', os.homedir());
// Standalone ESM-based Node.js script on Unix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment