【问题标题】:Download Module on NPM start在 NPM 启动时下载模块
【发布时间】:2017-12-10 09:27:30
【问题描述】:

我想知道在其他代码运行之前是否有一种简单的方法可以下载文件。我需要首先从我的服务器下载 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 上同步下载该文件的最佳方式是什么?

【问题讨论】:

    标签: node.js asynchronous synchronous


    【解决方案1】:

    您可以使用 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);
    

    pre-start.js:

    const fs = require('fs');
    
    setTimeout(function() {
        const value = {
            "one" : 1,
            "two" : 2
        };
    
        fs.writeFileSync('new-file.json', JSON.stringify(value));
    }, 1000)
    

    这里是文章的链接,其中包含更多详细信息: 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
        }
    });
    

    【讨论】:

    • 谢谢。正是我需要的。
    猜你喜欢
    • 2020-02-16
    • 2011-04-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    相关资源
    最近更新 更多