Created
April 10, 2016 10:36
-
-
Save adasq/a28ca1032bf5a476db0b04c36defde5f to your computer and use it in GitHub Desktop.
npm-shrinkwrap.json
This file contains hidden or 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
var fs = require('fs'), | |
path = require('path'), | |
npmShrinkwrapJson; | |
const NPM_SHRINKWRAP_PATH = path.join(__dirname, './npm-shrinkwrap.json'), | |
JSON_INDENT = ' '; | |
IGNORED_FIELDS = ['from', 'resolved']; | |
fs.readFile(NPM_SHRINKWRAP_PATH, function(err, npmShrinkwrapConent){ | |
if(err){ | |
return console.log(err); | |
} | |
npmShrinkwrapJson = parseJSON(npmShrinkwrapConent); | |
if(!npmShrinkwrapJson){ | |
return console.log(`could not parse ${NPM_SHRINKWRAP_PATH} as JSON`); | |
} | |
searchAndRemove(npmShrinkwrapJson.dependencies); | |
fs.writeFile(NPM_SHRINKWRAP_PATH+'2', JSON.stringify(npmShrinkwrapJson, null, JSON_INDENT), (err) => { | |
if(err){ | |
return console.log(err); | |
} | |
console.log('done.'); | |
}); | |
}); | |
/** | |
* It search recursive in object, and it's children objects | |
* for package description type object, | |
* and remove keys (contained in IGNORED_FIELDS) from it. | |
* @param {Object} object | |
*/ | |
function searchAndRemove(obj){ | |
if(isPackageDesc(obj)){ | |
removeIgnoredKeys(obj); | |
if(obj.dependencies){ | |
searchAndRemove(obj.dependencies); | |
} | |
} else { | |
//it's a list of dependencies | |
Object.keys(obj).forEach( (dependencyName) => { | |
searchAndRemove(obj[dependencyName]); | |
}); | |
} | |
} | |
/** | |
* determines, if given object is | |
* - package description object (true), or | |
* - list of dependencies object (false) | |
* @param {Object} object | |
* @return {Boolean} result | |
*/ | |
function isPackageDesc(obj){ | |
return (obj.version && typeof obj.version === 'string'); | |
} | |
/** | |
* removes keys stored in IGNORED_FIELDS from given object | |
* @param {Object} object | |
*/ | |
function removeIgnoredKeys(obj){ | |
IGNORED_FIELDS.forEach( (fieldNameToIgnore) => { | |
if(typeof obj[fieldNameToIgnore] === 'string'){ | |
delete obj[fieldNameToIgnore]; | |
} | |
}); | |
} | |
/** | |
* parses given str into JS object | |
* @param {String} str | |
* @return {Object} JS object | |
*/ | |
function parseJSON(str){ | |
var obj = null; | |
try{ | |
obj = JSON.parse(str); | |
}catch(err){} | |
return obj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment