1
我的代碼工作循環的罰款外:爲什麼我的服務器永遠不會收到Node.js中循環內部發出的任何請求?
var localFolder = '/home/transcripts',
apiHost = 'https://someserver'
apiCall = '/path',
sharedSecret = 'secret';
/* includes */
var sys = require('sys'),
fs = require('fs'),
exec = require('child_process').exec,
querystring = require('querystring'),
crypto = require('crypto')
request = require('request');
var file = "index_07_03_2013_1209576.csv";
console.log('Pushing CSV to API: ' + file);
var r = request.post(
apiHost + '/' + apiCall,
{ form: {
'filename': file,
'accessToken': crypto.createHash('md5').update(file + sharedSecret).digest('hex')
}
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
console.log(error);
console.log(response);
}
);
file = "index_07_02_2013_1548773.csv";
console.log('Pushing CSV to API: ' + file);
var r = request.post(
apiHost + '/' + apiCall,
{ form: {
'filename': file,
'accessToken': crypto.createHash('md5').update(file + sharedSecret).digest('hex')
}
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
console.log(error);
console.log(response);
}
);
file = "index_07_02_2013_1548773.csv";
console.log('Pushing CSV to API: ' + file);
var r = request.post(
apiHost + '/' + apiCall,
{ form: {
'filename': file,
'accessToken': crypto.createHash('md5').update(file + sharedSecret).digest('hex')
}
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
console.log(error);
console.log(response);
}
);
然而,當我嘗試將其移動到一個foreach循環,沒有請求過由服務器接收。我確實看到輸出表明CSV文件正在被推送到API,但請求似乎永遠不會觸及服務器。下面是該代碼:
#!/usr/local/bin/node
/* environment vars */
var localFolder = '/home/transcripts',
apiHost = 'https://someserver'
apiCall = '/path',
sharedSecret = 'secret';
/* includes */
var sys = require('sys'),
fs = require('fs'),
exec = require('child_process').exec,
querystring = require('querystring'),
crypto = require('crypto')
request = require('request');
var counter = 0;
fs.readdir(localFolder, function(err, files) {
files.forEach(function(file) {
if (file.substr(-3, 3) == 'csv') {
console.log('Pushing CSV to API: ' + file);
request.post(
apiHost + '/' + apiCall,
{ form: {
'filename': file,
'accessToken': crypto.createHash('md5').update(file + sharedSecret).digest('hex')
}
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
console.log(error);
console.log(response);
}
);
console.log(request);
}
counter++;
});
if (counter >= files.length) {
process.exit(0);
}
});
任何人有任何想法的問題可能是什麼?
標誌着我你的答案是正確的,因爲這個問題是調用process.exit()。我完全從我的腳本中刪除了這些東西(看起來並不需要,真的),它的功能就像一個魅力。謝謝一堆! – sluther