Last active
September 19, 2024 05:41
-
-
Save nichoth/35def0bf3e37fe0dd090f40bb3e43d9b to your computer and use it in GitHub Desktop.
Node tips
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Get the env variables from a file