Created
March 27, 2021 12:58
-
-
Save HollyPony/fbdf8913ce487d192a8cf4cb7cf9e85a to your computer and use it in GitHub Desktop.
auto-updater for `npm start` if `package.json` file change
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/package.lastInstall |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"scripts": { | |
"prestart": "node ./preinstall" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs') | |
let lastInstall = null | |
let lastModified = null | |
// Retrieve lastInstall date. If `package.lastInstall` not exist or error during rerieveing date, keep it `null` | |
try { lastInstall = fs.readFileSync('package.lastInstall', { encoding: 'utf8' }) } catch (error) {} | |
// Retrieve lastModified date on `package.json`. If `package.json` not exist or error during rerieveing date, keep it `null` | |
try { lastModified = String(fs.statSync('package.json').mtime.getTime()) } catch (error) {} | |
// If any is null or date no match, execute an `npm i` | |
if (!lastInstall || !lastModified || lastModified !== lastInstall) { | |
console.log('Updating ...') | |
require('child_process').execSync('npm i', { stdio: 'inherit' }) | |
lastModified = String(fs.statSync('package.json').mtime.getTime()) // Retrieve the new `lastModified` date due to `npm i` alteration | |
fs.writeFileSync('package.lastInstall', lastModified, { encoding: 'utf8' }) | |
console.log('Your system is up to date') | |
// If an error happen during this process, script failed and exit. Add a try catch if you want another beaviour | |
} else { | |
console.log('Your system is up to date') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment