Last active
December 3, 2023 22:01
-
-
Save vadimdemedes/1754e7adcb2b80a23945e9433d60045f to your computer and use it in GitHub Desktop.
detect-node
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/env node | |
import os from "node:os"; | |
import path from "node:path"; | |
import { $, execa } from "execa"; | |
import { locatePath } from "locate-path"; | |
import defaultShell from "default-shell"; | |
async function getShellProfile() { | |
const { homedir } = os.userInfo(); | |
if (defaultShell.endsWith("zsh")) { | |
return path.join(homedir, ".zshrc"); | |
} | |
const shellProfile = await locatePath([ | |
path.join(homedir, ".bashrc"), | |
path.join(homedir, ".bash_profile"), | |
path.join(homedir, ".profile"), | |
]); | |
return shellProfile ?? path.join(homedir, ".zshrc"); | |
} | |
async function getNodePathBare(cwd) { | |
const $$ = $({ | |
cwd, | |
}); | |
const { stdout } = await $$`which node`; | |
return stdout; | |
} | |
async function getNodePathWithoutProfile(cwd) { | |
const $$ = $({ | |
shell: defaultShell, | |
cwd, | |
}); | |
const { stdout } = await $$`which node`; | |
return stdout; | |
} | |
async function getNodePath(cwd) { | |
const shellProfile = await getShellProfile(); | |
const $$ = $({ | |
shell: defaultShell, | |
cwd, | |
}); | |
const { stdout } = await $$`source ${shellProfile} && which node`; | |
return stdout; | |
} | |
async function getSystemNodeVersion(cwd) { | |
const node = await getNodePath(cwd); | |
const { stdout, failed } = await execa(node, ["--version"], { | |
timeout: 3_000, | |
reject: false, | |
}); | |
return failed ? undefined : stdout.replace(/^v/, ""); | |
} | |
console.log("Default shell =", defaultShell); | |
console.log("This shell =", process.env["SHELL"]); | |
console.log("Shell profile =", await getShellProfile()); | |
console.log("Node path bare =", await getNodePathBare(process.cwd())); | |
console.log( | |
"Node path without profile =", | |
await getNodePathWithoutProfile(process.cwd()) | |
); | |
console.log("Node path =", await getNodePath(process.cwd())); | |
console.log("Node version =", await getSystemNodeVersion(process.cwd())); |
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
{ | |
"name": "detect-node", | |
"version": "1.0.0", | |
"description": "", | |
"type": "module", | |
"bin": "./index.js", | |
"dependencies": { | |
"default-shell": "2.2.0", | |
"execa": "7.1.1", | |
"locate-path": "7.2.0" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment