首页 > 解决方案 > 如何在 npm install 期间下载静态文件

问题描述

我的 Angular 应用程序中有一个链接,单击该链接应打开一个 pdf 文件。但是,应首先下载此文件并使其静态可用。

有没有办法在运行 npm install 时通过 http 请求下载文件?

基本上,在托管应用程序之前,我需要下载文件并将其复制到静态位置,然后从应用程序中的 href 引用该位置

就像是

npm download http://download.com/file.pdf

或者

instruct npm to download via paclage.json

标签: javascriptangularnpm

解决方案


postinstall您可以在应用程序的 package.json中定义一个 脚本:

包.json

{
  "name": "my-app",
  "version": "1.0.0",
  "scripts": {
    "start": "node src/index.js",
    "postinstall": "node downloadAssets.js", // <--------------------------
    // ...
  },
  "dependencies": { /* ... */ }
  // ...
}

然后创建一个脚本来执行此操作:

下载Assets.js

const http = require('http');
const fs = require('fs');

const file = fs.createWriteStream("file.pdf");
http.get("http://download.com/file.pdf", function(response) {
  response.pipe(file);
});

它将在您安装应用程序时执行(安装完所有内容后)


推荐阅读