Skip to content

Instantly share code, notes, and snippets.

@nichoth
Last active June 25, 2024 23:47
Show Gist options
  • Save nichoth/35def0bf3e37fe0dd090f40bb3e43d9b to your computer and use it in GitHub Desktop.
Save nichoth/35def0bf3e37fe0dd090f40bb3e43d9b to your computer and use it in GitHub Desktop.
Node tips
#!/usr/bin/node // shebang
//
// mkdir -p
//
const fs = require('node:fs/promises')
// Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.
await fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
if (err) throw err;
});
// ----------------------------------------------------
//
// Is this file running because it was called via CLI?
// (ESM edition)
//
import { resolve } from 'path'
import { fileURLToPath } from 'url'
const pathToThisFile = resolve(fileURLToPath(import.meta.url))
const pathPassedToNode = resolve(process.argv[1])
const isThisFileBeingRunViaCLI = pathToThisFile.includes(pathPassedToNode)
// ----------------------------------------------------
//
// __dirname
//
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment