Reputation: 4089
I have a JS app that I am working on and am using many open-source dependencies. I need to create a page that contains the license information for each package. My app currently has the ability to read a list of licenses from a JSON file and render it. I do not want to create this file by hand because it is tedious and can easily get outdated. Luckily, all the dependencies are listed in my package.json so it should theoretically be easy to generate it programatically, unfortunately I am yet to find a way.
It looks like almost everything has a "LICENSE" file in the root directory of its repository so what could work is if I had a gulp script that could download and process each of these files. Unfortunately I have not been able to find a way to query NPM for the repository address of a package programatically. How does one achieve that?
Upvotes: 4
Views: 6075
Reputation: 1274
I have done this, feel free to adapt it for your use case (just run it with node on the project directory (node getLicenses.js > LICENSES.txt
):
const FS = require('fs');
const packageJSON = JSON.parse(FS.readFileSync('package.json').toString());
const dependencies = packageJSON.dependencies;
const LICENSE_NAMES = [
'LICENSE',
'license',
'LICENSE.md',
];
let FAILED_TO_FIND_LICENSES = false;
let libraries = Object.keys(dependencies);
libraries.forEach(key => {
console.log('\n' + key);
console.log('================================');
const path = 'node_modules/' + key;
let license = null;
LICENSE_NAMES.forEach(name => {
try {
license = FS.readFileSync(path + '/' + name).toString();
} catch (e) {}
});
if (!license) {
try {
let libraryPackageFile = FS.readFileSync(path + '/package.json').toString();
// You can try to get the license from the package.json here
} catch (e) {}
}
if (license) {
console.log(license);
} else {
console.log('License not found');
FAILED_TO_FIND_LICENSES = true;
try { // This is to help update the LICENSE_NAMES before re-run it
let files = FS.readdirSync(path);
files.forEach(file => {
console.log(file);
});
} catch (e) {}
}
});
if (FAILED_TO_FIND_LICENSES) {
console.error('WARN: The license for some dependencies was not found!');
}
Upvotes: 0
Reputation: 4089
I finally found https://www.npmjs.com/package/get-repository-url which does what I want.
Upvotes: 0
Reputation: 34233
It's going to be tough to do it on your own reliably. AFAIK, publishers of npm packages are not required to supply licenses, or at least not in a standard way.
Fortunately, this package is able to display license information for all packages found in node_modules
. It also has a simple API so it should be fairly easy to get the info and display it on a web page.
Upvotes: 1