0
我寫了一個名爲deploy.js的文件,它通過它的API將文件夾的所有文件上傳到github。它需要兩個參數 - 您想要上傳的用戶和文件夾的accessToken。我通過passport-github獲得訪問令牌。我有一個主要的app.js文件,deploy.js可以通過變量deploy獲得。 App.js有一個路由/what
,它調用了部署功能。問題是下面的代碼有效。發送響應後異步函數無法正確執行
app.get('/what', function(req, res) {
//req.user.token contains the oauth token of the user
deploy(req.user.token, folder, function() {
res.send("completed");
});
});
但如果我把回調res.send()
之外,它並沒有完全執行。
app.get('/what', function(req, res) {
deploy(req.user.token, folder, function() {
console.log("deploy completed");
});
res.send("Work being done");
})
這是我寫的deploy.js文件。我已經使用了npm-github
圖書館爲節點封裝本地github API.
var distHelper = require('./dist.js');
var fs = require('fs');
var path = require('path');
var github = require('github');
var gh = new github();
module.exports = function(accessToken, folder, callback) {
//Authenticating using the oauth accessToken received above
gh.authenticate({ type:"oauth", token: accessToken});
var fullPath = distHelper.distPath + "/" + folder;
var eventName = folder.substr(folder.search("/") + 1);
//the below function returns a list of all files in a directory recursively
var walk = function(dir, done) {
var results = [];
fs.readdir(dir, function(err, list) {
if (err) return done(err);
var i = 0;
(function next() {
var file = list[i++];
if (!file) return done(null, results);
file = dir + '/' + file;
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
walk(file, function(err, res) {
results = results.concat(res);
next();
});
} else {
results.push(file);
next();
}
});
})();
});
};
//creating a repo
gh.repos.create({name: 'b', auto_init: 1}, function(err, response) {
if(err) {
console.log(err);
}
walk(fullPath, function(err, results) {
if(err) {
console.log(err);
}
//Base64 encoding of a file
function encode(file) {
var bitmap = fs.readFileSync(file);
return new Buffer(bitmap).toString('base64');
}
//Function which uploads file to the github one by one
function doOne() {
var elem = results.shift();
var fileName = elem.substr(elem.search(eventName)+eventName.length + 1);
console.log(fileName);
gh.repos.createFile({owner: "princu7", repo: "b", path: fileName, message: "please work", content:encode(elem)}, function(err, res) {
if(err) {
console.log(err);
}
else {
console.log("got response");
}
if(results.length > 0) {
doOne();
}
else {
// when all files are finished uploading, then the below function is called
callback();
}
});
}
doOne();
});
});
};
各地我已經撞了我的頭撞在牆上尋找原因,但我一直沒能找到任何。這可能與封鎖有關,但我不確定。如果有人願意幫忙,我會很感激。謝謝。
因爲'node.js'是異步的。 –
這是一個'I/O',應該是'async',你必須在'deploy'函數中發送你的響應。你可以看到[這裏](http://stackoverflow.com/questions/41401902/send-variables-to-layout/41402223#41402223)瞭解更多信息。 –
我知道,但我不明白你在指出什麼。在第一種情況下,它運行良好。在第二種情況下,它最初運行,然後掛起一點。即使在res.send()之後,部署函數應該繼續運行?請有人糾正我。 –