Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 在NPM启动时下载模块_Node.js_Asynchronous_Synchronous - Fatal编程技术网

Node.js 在NPM启动时下载模块

Node.js 在NPM启动时下载模块,node.js,asynchronous,synchronous,Node.js,Asynchronous,Synchronous,我想知道是否有一种简单的方法可以在其他代码运行之前下载文件。我需要先从我的服务器下载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); });

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

您可以使用npm脚本预挂钩获得这样的结果

假设您的启动脚本名为“start”,则在package.json中添加 名为“prestart”的脚本,您希望在其中运行执行文件下载的脚本。当您调用
npm run start

例如:

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)
以下是一个链接,指向包含更详细信息的文章:

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

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
    }
});

非常感谢。正是我需要的。