Marvin Danig
Marvin Danig

Reputation: 3918

Display license on package install node

How to use npm scripts and a postinstall hook to display the license of an npm package. Right now I'm doing it with:

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "postinstall": "cat ./MIT-license.txt"
  },

on the package.json. But this fails on windows because, well, cat. I know that we can use type on windows to output the contents of a file over the console, but how to do that in an npm script (without failing cat on windows and type on unix/mac)?

Upvotes: 3

Views: 229

Answers (1)

McMath
McMath

Reputation: 7188

If i understand correctly, you need a cross-platform mechanism for logging the contents of a file to the console. I think the easiest way to do this is via a custom Node script, since you know the user will have Node installed, whatever their operating system.

Just write a script like this:

// print-license.js
'use strict';

const fs = require('fs');

fs.readFile('./MIT-license.txt', 'utf8', (err, content) => {
  console.log(content);
});

And then, in your package.json:

// package.json
"scripts": {
  "postinstall": "node ./print-license.js"
},

Or, if you don't want a serparate script hanging around, this is just about short enough to do inline, like so:

// package.json
"scripts": {
  "postinstall": "node -e \"require('fs').readFile('./MIT-license.txt', 'utf8', function(err, contents) { console.log(contents); });\""
},

Update

And now that I think about it, you might be better off with a reusable executable that would allow you to specify a file as a command line argument. That's also very simple:

// bin/printfile
#!/usr/bin/env node
'use strict';

const FILE = process.argv[2];

require('fs').readFile(FILE, 'utf8', (err, contents) => {
  console.log(contents);
});

And add the following to your package.json:

// package.json
"bin": {
  "printfile": "./bin/printfile"
},
"scripts": {
  "postinstall": "printfile ./MIT-license.txt"
}

Upvotes: 3

Related Questions