首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何修复Node.js抛出er;//未处理的'error‘事件

如何修复Node.js抛出er;//未处理的'error‘事件
EN

Stack Overflow用户
提问于 2021-02-09 23:46:19
回答 1查看 115关注 0票数 0

我正在学习Node.js,我刚刚创建了一个表单,当我发出post请求时,我的节点js脚本将执行一个终端命令来使用gradle进行构建。默认情况下,我使用index.html来显示表单,一旦构建完成,我希望显示build.html页面。

但我得到了一个错误,

我的代码:

代码语言:javascript
复制
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');

错误:

代码语言:javascript
复制
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)

如何修复此错误,如何在构建成功后显示build.html页面。

提前感谢!

EN

回答 1

Stack Overflow用户

发布于 2021-02-10 00:06:06

错误堆栈上正在显示错误消息字符串:

代码语言:javascript
复制
Error: write after end

readable.pipe在可写流上调用end。在这种情况下,我相信您的两个文件读取流之间存在竞争条件。

代码语言:javascript
复制
/*****************************************************/
/*  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);

我相信如果最后一个流不是POST,你会想要发送它,所以你可以为任何其他类型的请求添加else子句:

代码语言:javascript
复制
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')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66122333

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档