Commit 07ef023

Anton Medvedev <anton@medv.io>
2021-05-12 23:11:23
Add __filename & __dirname
1 parent 7cf5b43
README.md
@@ -200,6 +200,13 @@ Specifies verbosity. Default: `true`.
 In verbose mode prints executed commands with outputs of it. Same as 
 `set -x` in bash.
 
+### `__filename` & `__dirname`
+
+In [ESM](https://nodejs.org/api/esm.html) modules, Node.js does not provide
+`__filename` and `__dirname` globals. As such globals really handy in scripts,
+`zx` provides such globals, so they can be used in `.mjs` files (via using `zx`
+binary).
+
 ### Importing from other scripts
 
 It's possible to use `$` and others with explicit import.
test.mjs
@@ -68,4 +68,8 @@ import {strict as assert} from 'assert'
   await $`echo $FOO`
 }
 
+{
+  console.log(__filename, __dirname)
+}
+
 console.log(chalk.green('🍺 Success!'))
zx.mjs
@@ -14,7 +14,7 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-import {join, basename} from 'path'
+import {join, basename, resolve, dirname} from 'path'
 import os, {tmpdir} from 'os'
 import {promises as fs} from 'fs'
 import url from 'url'
@@ -55,7 +55,7 @@ try {
     } else {
       path = join(process.cwd(), firstArg)
     }
-    await import(url.pathToFileURL(path))
+    await importPath(path)
   }
 
 } catch (p) {
@@ -104,3 +104,10 @@ async function writeAndImport(filepath, script) {
     await fs.rm(filepath)
   }
 }
+
+async function importPath(filepath) {
+  let __filename = resolve(filepath)
+  let __dirname = dirname(__filename)
+  Object.assign(global, {__filename, __dirname})
+  await import(url.pathToFileURL(filepath))
+}