我的代码在循环之外工作正常:
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);
}
});
任何人都有任何想法可能是什么问题?