【问题标题】:Display license on package install node在包安装节点上显示许可证
【发布时间】:2016-02-21 14:09:33
【问题描述】:

如何使用npm 脚本和postinstall 挂钩来显示npm 包的许可证。现在我正在这样做:

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

package.json 上。但这在 Windows 上失败了,因为cat。我知道我们可以在 Windows 上使用 type 通过控制台输出文件的内容,但是如何在 npm 脚本中执行此操作(在 Windows 上 cat 和在 unix/mac 上 type 不会失败)?

【问题讨论】:

    标签: node.js npm npm-install


    【解决方案1】:

    如果我理解正确,您需要一种跨平台机制来将文件的内容记录到控制台。我认为最简单的方法是通过自定义 Node 脚本,因为您知道用户将安装 Node,无论他们的操作系统是什么。

    只要写一个这样的脚本:

    // print-license.js
    'use strict';
    
    const fs = require('fs');
    
    fs.readFile('./MIT-license.txt', 'utf8', (err, content) => {
      console.log(content);
    });
    

    然后,在你的 package.json 中:

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

    或者,如果你不想要一个单独的脚本,这只是足够短的内联,就像这样:

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

    更新

    现在我考虑了一下,使用可重用的可执行文件可能会更好,它允许您将文件指定为命令行参数。这也很简单:

    // bin/printfile
    #!/usr/bin/env node
    'use strict';
    
    const FILE = process.argv[2];
    
    require('fs').readFile(FILE, 'utf8', (err, contents) => {
      console.log(contents);
    });
    

    并将以下内容添加到您的 package.json 中:

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

    【讨论】:

    • 我觉得前者很干净。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    • 2013-02-25
    • 2021-08-19
    相关资源
    最近更新 更多