Skip to content

Instantly share code, notes, and snippets.

@HollyPony
Created March 27, 2021 12:58
Show Gist options
  • Save HollyPony/fbdf8913ce487d192a8cf4cb7cf9e85a to your computer and use it in GitHub Desktop.
Save HollyPony/fbdf8913ce487d192a8cf4cb7cf9e85a to your computer and use it in GitHub Desktop.
auto-updater for `npm start` if `package.json` file change
/package.lastInstall
{
"scripts": {
"prestart": "node ./preinstall"
}
}
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