aboutsummaryrefslogtreecommitdiffstats
path: root/npm.js
blob: 5242eeb4f039153b5082542f87853f3f712dfeea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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
  };
};