简体   繁体   English

如何修复 Node.js 投掷器; // 未处理的“错误”事件

[英]How to fix Node.js throw er; // Unhandled 'error' event

I'm learning Node.js, I just created a form, when I make post request my node js script will execute one terminal command to build using gradle.我正在学习 Node.js,我刚刚创建了一个表单,当我发出发布请求时,我的节点 js 脚本将执行一个终端命令来使用 gradle 进行构建。 By default I use index.html to show form, Once my build is completed I want to show build.html page.默认情况下,我使用 index.html 来显示表单,一旦我的构建完成,我想显示 build.html 页面。

But I'm getting error,但我得到错误,

My code:我的代码:

const http = require('http');
const fs = require('fs');
const { spawn } = require("child_process");
var qs = require('querystring');
const server = http.createServer((req, res)=> {
    if (req.method == 'POST') {
        var body = '';
        console.log("Post received");
        
        req.on('data', function (data) {

            body += data;
            var post = qs.parse(body);


            // Too much POST data, kill the connection!
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6)
                req.connection.destroy();
        });

        req.on('end', function () {
            var post = qs.parse(body);
            // use post['blah'], etc.


            const ls = spawn("./gradlew", ["build"]);
            
            ls.stdout.on("data", data => {
               // console.log(`stdout: ${data}`);
            
            });
            
            ls.stderr.on("data", data => {
                console.log(`stderr: ${data}`);
            });
            
            ls.on('error', (error) => {
                console.log(`error: ${error.message}`);
            });
            
            ls.on("close", code => {
               //console.log(`child process exited with code ${code}`);
            console.log("Build success");
        const readStream = fs.createReadStream('./build.html');
res.writeHead(200, {'Content-type': 'text/html'});
readStream.pipe(res);


            });
            
                        
        });

        
    }

const readStream = fs.createReadStream('./index.html');
res.writeHead(200, {'Content-type': 'text/html'});
readStream.pipe(res);

});
server.listen('3000');

Error:错误:

events.js:183
      throw er; // Unhandled 'error' event
      ^

Error: write after end
    at write_ (_http_outgoing.js:622:15)
    at ServerResponse.write (_http_outgoing.js:617:10)
    at ReadStream.ondata (_stream_readable.js:639:20)
    at emitOne (events.js:116:13)
    at ReadStream.emit (events.js:211:7)
    at addChunk (_stream_readable.js:263:12)
    at readableAddChunk (_stream_readable.js:250:11)
    at ReadStream.Readable.push (_stream_readable.js:208:10)
    at fs.read (fs.js:2051:12)
    at FSReqWrap.wrapper [as oncomplete] (fs.js:658:17)

How I can fix this error, How to show the build.html page once the build is successful.如何修复此错误,如何在构建成功后显示 build.html 页面。

Thanks in advance!提前致谢!

The error message string is being displayed on the error stack:错误消息字符串显示在错误堆栈上:

Error: write after end

readable.pipe calls end on the writable stream. readable.pipe的。pipe 在可写的 stream 上调用end In this case I believe you have a race condition between both of your file read streams.在这种情况下,我相信您的两个文件读取流之间存在竞争条件。

/*****************************************************/
/*  First Stream                                     */
/*****************************************************/
console.log("Build success");
const readStream = fs.createReadStream('./build.html');
res.writeHead(200, {
    'Content-type': 'text/html'
});
readStream.pipe(res);

/*****************************************************/
/*  Second Stream                                    */
/*****************************************************/

const readStream = fs.createReadStream('./index.html');
res.writeHead(200, {'Content-type': 'text/html'});
readStream.pipe(res);

I believe you'd want the last stream only sent if it's not POST so you could add an else clause for any other type of request:我相信您希望仅在不是POST时才发送最后一个 stream ,因此您可以为任何其他类型的请求添加 else 子句:

const http = require('http');
const fs = require('fs');
const {
    spawn
} = require("child_process");
var qs = require('querystring');
const server = http.createServer((req, res) => {
    if (req.method == 'POST') {
        var body = '';
        console.log("Post received");

        req.on('data', function(data) {

            body += data;
            var post = qs.parse(body);


            // Too much POST data, kill the connection!
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6)
                req.connection.destroy();
        });

        req.on('end', function() {
            var post = qs.parse(body);
            // use post['blah'], etc.


            const ls = spawn("./gradlew", ["build"]);

            ls.stdout.on("data", data => {
                // console.log(`stdout: ${data}`);

            });

            ls.stderr.on("data", data => {
                console.log(`stderr: ${data}`);
            });

            ls.on('error', (error) => {
                console.log(`error: ${error.message}`);
            });

            ls.on("close", code => {
                //console.log(`child process exited with code ${code}`);
                console.log("Build success");
                const readStream = fs.createReadStream('./build.html');
                res.writeHead(200, {
                    'Content-type': 'text/html'
                });
                readStream.pipe(res);


            });


        });
    } else {
        const readStream = fs.createReadStream('./index.html');
        res.writeHead(200, {
            'Content-type': 'text/html'
        });
        readStream.pipe(res);
    }
});
server.listen('3000')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM