以下内容有效,但似乎我缺少了一点数据。实现我在这里想要做的最好的方法是什么。我运行node updateFiles.js 5.5.9
,闪电般快,但是就像我说的那样,当我盯着结果文件时,似乎错过了一些块……?
下面是updateFiles.js
的内容。
const fs = require('fs');
const fetch = require('node-fetch');
var version = process.argv[2];
var filePath = 'source/js/firebase.js';
var sdks = [
'https://www.gstatic.com/firebasejs/' + version + '/firebase-app.js',
'https://www.gstatic.com/firebasejs/' + version + '/firebase-auth.js',
'https://www.gstatic.com/firebasejs/' + version + '/firebase-database.js',
'https://www.gstatic.com/firebasejs/' + version + '/firebase-firestore.js',
'https://www.gstatic.com/firebasejs/' + version + '/firebase-messaging.js',
'https://www.gstatic.com/firebasejs/' + version + '/firebase-functions.js'
];
//fetch each firebase file and write it to source/js/firebase.js
for (var sdk of sdks){
fetch(sdk).then(res => {
const dest = fs.createWriteStream(filePath,{flags:'a'});
res.body.pipe(dest);
});
}
更新:我最终这样做了,而且似乎可行,但是,如果那里有一个专家可以指出更好的方法,请告诉我。预先谢谢你。
const fs = require('fs');
const fetch = require('node-fetch');
var version = process.argv[2];
var promisesArray = [];
var sdks = [
// Firebase App is always required and must be first
'https://www.gstatic.com/firebasejs/' + version + '/firebase-app.js',
// Add additional services that you want to use
'https://www.gstatic.com/firebasejs/' + version + '/firebase-auth.js',
'https://www.gstatic.com/firebasejs/' + version + '/firebase-database.js',
'https://www.gstatic.com/firebasejs/' + version + '/firebase-firestore.js',
'https://www.gstatic.com/firebasejs/' + version + '/firebase-messaging.js',
'https://www.gstatic.com/firebasejs/' + version + '/firebase-functions.js'
];
var filePath = 'source/js/firebase.js';
for (var sdk of sdks){
promisesArray.push(fetch(sdk));
}
Promise.all(promisesArray).then(sdkFiles => {
for (var file of sdkFiles){
const dest = fs.createWriteStream(filePath,{flags:'a'});
file.body.pipe(dest);
}
});
答案 0 :(得分:0)
也许您不能一次写入所有文件,而是等待每个文件被处理然后继续处理另一个文件?来自循环的承诺来自:JavaScript ES6 promise for loop
for (let i = 0, p = Promise.resolve(); i < sdks.length; i++) {
p = p.then(_ => new Promise(resolve =>
fetch(sdks[i]).then(res => {
const dest = fs.createWriteStream(filePath, { flags: 'a' });
res.body.pipe(dest);
resolve()
})
));
}