UNPKG

npm-auto-update

Version:

check for update and update npm dependencies

106 lines (95 loc) 3.48 kB
"use strict"; const path = require('path'); const fs = require('fs'); const os = require('os'); const rimraf = require('rimraf'); class NpmAutoUpdate { constructor (log, local, testMode) { this.packagePath = './../../package.json'; if (testMode) { this.packagePath = './package.json'; } this.global = !local; this.gitPath = path.join(__dirname, "./../../.git/"); this.appPath = path.join(__dirname, "./../../"); this.log = log; this.exec = require('child_process').exec; this.packageJsonPath = path.join(__dirname, this.packagePath); this.packageJson = JSON.parse(fs.readFileSync(this.packageJsonPath)); this.sudo = "sudo "; if (os.type() == "Windows_NT") { this.sudo = ""; } } getLocalVersion () { return this.packageJson.version; } getPackageName () { return this.packageJson.name; } getNpmVersion (callback) { const cmd = 'npm view ' + this.getPackageName() + ' version'; this.exec(cmd, (error, stdout) => { if (error) { this.log.error("Update Cancelt! "+error); callback(true, false); return; } let npm_version = stdout; if (!npm_version) npm_version = "0"; callback(error, npm_version); }); } checkForUpdate (callback) { this.getNpmVersion((error, npmVersion) => { if(error) { return; } npmVersion = npmVersion.replace('\n', ''); this.log.info("Version check for %s", this.getPackageName()); this.log.info("npm version is %s, your local version is %s", npmVersion, this.getLocalVersion()); if (npmVersion <= this.getLocalVersion()) { callback(false, false); } if (npmVersion > this.getLocalVersion()) { const response = "There is a new version available. Please update with sudo npm -g update " + this.getPackageName(); this.log.warn(response); callback(false, true); } }); } updatePackage (callback) { this.existsPath(this.gitPath, (result) => { if (!result) { this.update(callback); return; } rimraf(this.gitPath, () => { this.update(callback); }); }); } update (callback) { this.log.info("Upgrading now .. this may take some time."); let cmd = this.sudo + "npm -g update " + this.getPackageName(); if(!this.global) { cmd = "cd " + this.appPath + ";npm update " + this.getPackageName(); } this.exec(cmd, (error, stdout) => { if (error) { this.log.error(error); callback(true, false); return; } this.log.warn("A new version was installed recently. Please restart your node to complete the update"); this.log.info("Message from updater %s", stdout); callback(false, true); }); } existsPath (path, callback) { fs.access(path, fs.F_OK, function (err) { callback(!err); }); } } module.exports = NpmAutoUpdate;