Skip to content

Instantly share code, notes, and snippets.

@ArtemAvramenko
Last active October 11, 2023 11:47
Show Gist options
  • Save ArtemAvramenko/21f62d48fb0e34627acf30bb3436f2bc to your computer and use it in GitHub Desktop.
Save ArtemAvramenko/21f62d48fb0e34627acf30bb3436f2bc to your computer and use it in GitHub Desktop.
A standalone single-file Node.js script that installs dependencies locally in dotfiles
/**
* This small function allows you to distribute your script as a single file, without
* requiring a separate package.json. When running a script through a node, the dependencies
* that are installed will not affect neighboring scripts or global packages.
* @summary Installs dependencies in the local dotfiles folder
*/
const installDependencies = dependencies => {
const fs = require('fs');
const dependenciesPath = './.npm-' + __filename.match(/[^\\/]+$/)[0];
fs.existsSync(dependenciesPath) || fs.mkdirSync(dependenciesPath);
const packageFile = dependenciesPath + '/package.json';
const oldPackage = fs.existsSync(packageFile) && JSON.parse(fs.readFileSync(packageFile));
if (JSON.stringify(oldPackage.dependencies) !== JSON.stringify(dependencies)) {
fs.writeFileSync(packageFile, JSON.stringify({ dependencies }, null, ' '));
require('child_process').execSync('npm i', { stdio: 'inherit', cwd: dependenciesPath });
}
process.env.NODE_PATH = dependenciesPath + '/node_modules';
require('module').Module._initPaths();
};
// A simple usage example:
installDependencies({
'lodash': '^4.0.0',
'moment': '^2.0.0'
});
const { sortBy } = require('lodash');
const moment = require('moment');
const dates = sortBy(
['2000-12-31','2000-01-01'],
s => moment(s).valueOf());
console.log(dates);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment