Skip to content

Instantly share code, notes, and snippets.

@nichoth
Last active September 19, 2024 05:41
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)
// -------------------------------------------------------
//
// __rm -rf / rimraf__
//
// @see https://nodejs.org/api/fs.html#fspromisesrmdirpath-options --
// > To get a behavior similar to the rm -rf Unix command, use
// > fsPromises.rm() with options { recursive: true, force: true }.
//
import { fs } from 'fs/promises'
await fs.rm('my-file.txt', { recursive: true, force: true })
//
// Set the working directory
//
import process from 'node:process'
process.chdir(__dirname)
@nichoth
Copy link
Author

nichoth commented Sep 19, 2024

Get the env variables from a file

export $(cat .env | grep -e '^[^#]*$') | xargs && esbuild ...

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