Невозможно установить заголовки после отправки node.js

Я пытаюсь объединить несколько текстовых файлов, преобразовать их в один zip-файл с помощью zip-архиватора.

   exports.downloadFilesInZip = function(req, res, next) {

var respObj = {};
var file_names = [];
    var projectId = 111;
    var file_ids = 11111;
    console.log(projectId);
    db.getConnection(function (err, connection) {
        if (err) {
            debug(err);
            next(err);
        }
        else {
            var updateQuery = "select data from file_data where file_id IN (?)";
            console.log(updateQuery);
            connection.query(updateQuery,[file_ids], function (err, results) {
                console.log("inside" + updateQuery);

                if (err) {
                    connection.release();
                    console.log("error" + JSON.stringify(err));
                    debug(err);
                    next(err);
                }
                else {
                    async.eachSeries(results,function(item,loopCallBack){
                        var text = "";
                        console.log("hllllllll");
                        console.log(item.data);
                        console.log(JSON.parse(item.data));
                        document_text = JSON.parse(item.data);
                        console.log("dssddssdsdsdsdsd"+document_text);
                        for(var j=0; j < document_text.length ;j++)
                        {
                            text += document_text[j]['text'];
                        }

                        //file_names.push(convertStringToTextFile(text));
                        convertStringToTextFile(text,function(err,file_name){
                            if(err){
                                console.log(err);
                                loopCallBack(err);
                            }
                            else {
                                file_names.push(file_name);
                                loopCallBack();
                            }
                        })

                    },function(err){
                        if(err){
                            console.log(err);
                            next(err);
                        }
                        else {
                            var updateQuery = "select name from project where id in (?)";
                            console.log(updateQuery);
                            connection.query(updateQuery,[projectId], function (err, results) {
                                console.log("inside" + updateQuery);
                                connection.release();
                                if (err) {
                                    console.log("error" + JSON.stringify(err));
                                    debug(err);
                                    next(err);
                                }
                                else {
                                    var fileName_link = JSON.stringify(results[0].name);

                                    console.log("projectname"+fileName_link);
                                    convertTextFilesToZip(file_names,fileName_link, function (err, filename) {
                                        if (err) {
                                            console.log(err);
                                            next(err);
                                        }
                                        else {
                                            console.log("filename link" + filename);
                                            res.json({
                                                status: 0,
                                                file_link: filename
                                            });
                                        }
                                    });
                                }
                            });
                        }

                    });

                }
            });

        }
    });
}

}

convertStringToTextFile = function(text,cb){
var json_filename = 'tmp/file_'+uuid.v4().replace('-','')+'.txt';
fs.writeFile(json_filename, text , function (err) {
    if (err) {
        debug(err);
        cb(err);
    }
    else{
        cb(null,json_filename);
    }
});

};

convertTextFilesToZip = function(textFiles,file_link,cb){
console.log("textfiles"+textFiles);
var filename = 'reports/'+JSON.parse(file_link)+'_extractedText.zip';
var output = fs.createWriteStream(filename);

output.on('close', function() {
    console.log(zipArchive.pointer() + ' total bytes');
    console.log('archiver has been finalized and the output file descriptor has closed.');
});

zipArchive.on('error', function(err) {
    cb(err);
});

zipArchive.pipe(output);

zipArchive.bulk([
    { expand: true, src: textFiles }
]);

zipArchive.finalize();
cb(null,filename);


}

Он работает нормально в первый раз, а после этого выдает эту ошибку. Я проверил другие сообщения, в которых res возвращается дважды, но я не смог его найти. В нем говорится, что не удается установить заголовки после их отправки. Я думаю, что проблема находится в функции convertTextFilesToZip, но я, похоже, не могу определить точное место, которое вызывает ошибку. Любая помощь приветствуется.

  Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:350:11)
at ServerResponse.header     (/Users/zeeshandar/Desktop/Agreements_info/agreements_info/node_modules/express/lib/response.js:700:10)
at ServerResponse.send (/Users/zeeshandar/Desktop/Agreements_info/agreements_info/node_modules/express/lib/response.js:154:12)
at fn (/Users/zeeshandar/Desktop/Agreements_info/agreements_info/node_modules/express/lib/response.js:934:10)
at View.exports.renderFile [as engine] (/Users/zeeshandar/Desktop/Agreements_info/agreements_info/node_modules/jade/lib/index.js:374:12)
at View.render (/Users/zeeshandar/Desktop/Agreements_info/agreements_info/node_modules/express/lib/view.js:93:8)
at EventEmitter.app.render (/Users/zeeshandar/Desktop/Agreements_info/agreements_info/node_modules/express/lib/application.js:566:10)
at ServerResponse.res.render (/Users/zeeshandar/Desktop/Agreements_info/agreements_info/node_modules/express/lib/response.js:938:7)
at /Users/zeeshandar/Desktop/Agreements_info/agreements_info/app.js:207:13
at Layer.handle_error (/Users/zeeshandar/Desktop/Agreements_info/agreements_info/node_modules/express/li b/router/layer.js:58:5)

person soldiershin    schedule 02.05.2016    source источник
comment
Ничего себе, если бы когда-нибудь из учебников можно было использовать обещания для серии асинхронных операций, чтобы сделать код намного чище и намного проще обрабатывать ошибки, это был бы отличный пример.   -  person jfriend00    schedule 02.05.2016
comment
Если convertTextFilesToZip() откуда взялась переменная zipArchive?   -  person jfriend00    schedule 02.05.2016
comment
Он инициализирован в коде, который я только что не скопировал здесь   -  person soldiershin    schedule 02.05.2016
comment
Инициализировано где? Он не инициализирован в convertTextFilesToZip(), поэтому кажется, что вы снова и снова используете эту переменную. Это правильная реализация? Кроме того, не будут ли все операции zipArchive асинхронными?   -  person jfriend00    schedule 02.05.2016
comment
@ jfriend00 Ага, вы были правы, это действительно была проблема. Большое спасибо .. :)   -  person soldiershin    schedule 02.05.2016


Ответы (1)


Превращаю свой комментарий в ответ, поскольку он, похоже, привел к решению.

Переменная zipArchive не инициализирована в convertTextFilesToZip(), поэтому вы повторно используете эту переменную от одного вызова функции к другому, и это вряд ли будет правильной реализацией.

Кроме того, я бы ожидал, что вызовы ваших методов в zipArchive будут асинхронными, и это не похоже на то, что вы кодируете для этого, поскольку обратный вызов вызывается до того, как у вас появится какое-либо уведомление о завершении.

person jfriend00    schedule 02.05.2016