aboutsummaryrefslogtreecommitdiffstats
path: root/npm.js
diff options
context:
space:
mode:
authorJan Tuomi <jan.tuomi@eficode.com>2018-07-13 11:11:43 +0300
committerJan Tuomi <jan.tuomi@eficode.com>2018-07-13 11:11:43 +0300
commitbd993ccdf8aa2cadc3722d2d169386a7b24661c7 (patch)
tree050a27fa6e3d3788c2c9c67a200ec80d2c0eee0b /npm.js
parenta79413824414d1cda8341900becec1ea2b9d8617 (diff)
Fix tests
Diffstat (limited to 'npm.js')
-rw-r--r--npm.js76
1 files changed, 76 insertions, 0 deletions
diff --git a/npm.js b/npm.js
new file mode 100644
index 0000000..5242eeb
--- /dev/null
+++ b/npm.js
@@ -0,0 +1,76 @@
+const npm = require('npm');
+const intercept = require('intercept-stdout');
+
+module.exports = models => {
+ const npmLoad = () => new Promise((resolve, reject) => {
+ npm.load(err => {
+ if (err) {
+ reject(err);
+ }
+ resolve();
+ });
+ });
+
+ const npmList = () => new Promise((resolve, reject) => {
+ const unhookIntercept = intercept(() => '');
+ npm.config.set('depth', 0);
+ npm.commands.list([], (err, data) => {
+ unhookIntercept();
+ if (err) {
+ reject(err);
+ }
+ resolve(Object.keys(data._dependencies));
+ });
+ });
+
+ const npmInstall = packages => new Promise((resolve, reject) => {
+ const unhookIntercept = intercept(() => '');
+ npm.config.set('progress', 'false');
+ npm.config.set('silent', 'true');
+ npm.config.set('save', 'false');
+ npm.config.set('no-save', 'true');
+ npm.commands.install(packages, (err, data) => {
+ unhookIntercept();
+ if (err) {
+ reject(err);
+ }
+ resolve(data);
+ });
+ });
+
+ async function installPackagesFromDatabase(showInfo = false) {
+ try {
+ await npmLoad();
+ // Handle errors
+ const packagesToInstall = await models.packages.find({});
+ const packages = packagesToInstall.map(obj => obj.name.trim());
+
+ const installedPackages = await npmList();
+
+ packages.forEach(async pkg => {
+ if (installedPackages.some(installedPkg => installedPkg.includes(pkg))) {
+ if (showInfo) {
+ console.info(`"${pkg}" Already installed, skipping...`);
+ }
+ return;
+ }
+ console.info(`Installing package "${pkg}"...`);
+ // Install module
+ await npmInstall([pkg]);
+ });
+ if (showInfo) {
+ console.info(`Successfully installed ${packages.length} NPM packages programmatically.`);
+ }
+ } catch (err) {
+ console.error(`Failed to install NPM packages programmatically.`);
+ console.error(err);
+ }
+ }
+
+ return {
+ npmInstall,
+ npmList,
+ npmLoad,
+ installPackagesFromDatabase
+ };
+};