在NPM开始下载模块
我想知道在其他代码运行之前是否有简单的方法来下载文件。 我需要首先从我的服务器下载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); });
但是,如果我假设正确,该文件是asynchronous写入。 所以当我需要这个文件时,我只是空的对象或错误。
那么在npm start上首先同步下载这个文件的最好方法是什么?
你可以使用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);
预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 } });