在 NPM 启动时下载模块

Download Module on NPM start

我想知道是否有一种简单的方法可以在其他代码运行之前下载文件。我需要先从我的服务器下载 file.js,因为我在不同地方的应用程序中需要它。我知道我可以做那样的事情。

let file = fs.createWriteStream(path.join(__dirname, 'file.js'));
let request = http.get("http://expample.com/file.js",
    function(response) {
    response.pipe(file);
});

但如果我假设正确,文件是异步写入的。因此,当我需要该文件时,我只有空对象或错误。

那么首先在 npm start 上同步下载该文件的最佳方法是什么?

你可以使用 npm script pre hooks 得到这样的结果。

假设您的启动脚本名为 "start" ,在您的 package.json 添加 名为 "prestart" 的脚本,您想要 运行 执行文件下载的脚本。当您调用 npm run start

时,in 将自动为 运行

例如:

package.json :

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "prestart": "node pre-start.js"
  },
  "author": "",
  "license": "ISC"
}

index.js:

const value = require('./new-file.json');
console.log(value);

前start.js:

const fs = require('fs');

setTimeout(function() {
    const value = {
        "one" : 1,
        "two" : 2
    };

    fs.writeFileSync('new-file.json', JSON.stringify(value));
}, 1000)

这是一篇 link 文章,其中包含更详细的信息: http://www.marcusoft.net/2015/08/pre-and-post-hooks-for-npm-scripting.html

另一种方法是 运行 写入文件后的其他代码:

let file = fs.createWriteStream(path.join(__dirname, 'file.js'));
let request = http.get("http://expample.com/file.js",
    function(response) {
    response.pipe(file);
    file.on('finish',function(){
      // run your code here
    }
});