【发布时间】:2017-07-21 21:56:41
【问题描述】:
我的 MEEN 应用程序中有一个接受文件上传的路由,然后将数据传递给解析文件并将其存储在数组中的辅助模块,一旦这个辅助模块完成,我想将它传递给另一个模块然后将处理返回的数组。出于某种原因,即使我在帮助程序末尾有一个 return 语句,then 方法也是未定义的。
路线:
router.route('/tools/sku/reactivate').post(upload.single('csvdata'),function(req,res){
console.log('handing request over to helper.csv');
csv.reader(req,res).then(sku.reactivate(data));
});
csv.reader:
var csv = require('csv-parse');
var multer = require('multer');
var fs = require('fs');
module.exports.reader = function(req,res){
//define array for holding csv data in this case skus
const csvArray = [];
//max number of columns in csv
const maxColumns = parseInt(req.body.maxColumns);
//create an array of column headers to check chunks against so we dont parse headers
let columnHeader = req.body.moduleTarget.split(',');
//loopThrough Array to create arrays inside container array for each column
for(var i = 0; i < maxColumns; i++){
csvArray.push([]);
}
//define filesystem readstream from uploaded file
let readStream = fs.createReadStream(req.file.path).pipe(csv());
//push csv data to array ignoring headers to csvArray
readStream.on('data', function(chunk){
//get number of keys in the dataChunk
let chunkLength = Object.keys(chunk).length;
//check column count on csv if greater than expected throw error
if(chunk[maxColumns]){
throw '[ERROR] More columns than expected in CSV, please fix and try again';
}else{
//loop through chunk keys and store each one in csvArray by index
for(var i = 0; i < chunkLength; i++){
//if chunk at this index doesnt equal column header and chunk at this index exists push to array
if(chunk[i] !== columnHeader[i] && chunk[i]){
csvArray[i].push(chunk[i]);
}
}
}
});
//error handling
readStream.on('error',function(err){
console.log('Error while reading file stream '+ err);
res.json({message:err,errorType:'1'});
});
readStream.on('end',function(){
console.log('finished reading csv returning array back to router to process next middleware');
return csvArray;
});
}
我在 readStream 结束侦听器上的 console.log 消息后立即收到错误
【问题讨论】:
标签: javascript node.js express promise