Skip to content

Instantly share code, notes, and snippets.

@hMatoba

hMatoba/noman.md

Last active May 3, 2020
Embed
What would you like to do?

create ".envrc" for nvm or nodebrew

Needs some packages

jq && direnv && (nvm || nodebrew)

Run

npx https://gist.github.com/hMatoba/f13f91813e66c1d11d4246902a7f05f7
{"name": "noman", "version": "0.0.1", "bin": "./set.js"}
#!/usr/bin/env node
const spawnSync = require('child_process').spawnSync;
const process = require('process');
const fs = require('fs');
const hasNvm = () => {
const result = spawnSync('nvm', ['--version']);
return !!result.error;
};
const hasNodebrew = () => {
const result = spawnSync('nodebrew', ['help']);
return !!result.error;
};
const contentNvmrc = `
nvmrc=~/.nvm/nvm.sh
source $nvmrc
NODE_VER=$(cat package.json | jq -r ".engines.node")
nvm use $NODE_VER
`;
const contentNodebrew = `
NODE_VER=$(cat package.json | jq -r ".engines.node")
nodebrew use $NODE_VER
`;
const pathEnvrc = './.envrc'
const existsEnvrc = () => {
try {
fs.statSync(pathEnvrc);
return true;
} catch (error) {
if (error.code === 'ENOENT') {
return false;
} else {
console.error(error);
process.exit(1);
}
}
};
// processing -----------------------------------------------------------------
if (existsEnvrc()) {
console.log('exists ".envrc".');
process.exit(1);
}
if (hasNvm()) {
fs.writeFileSync(pathEnvrc, contentNvmrc);
console.log('execute "direnv allow && direnv reload"');
process.exit();
}
if (hasNodebrew()) {
fs.writeFileSync(pathEnvrc, contentNodebrew);
console.log('execute "direnv allow && direnv reload"');
process.exit();
}
console.error('install "nvm" or "nodebrew".');
process.exit(1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment