如何在node.js中结束HTTP响应正文

如何在node.js中结束HTTP响应正文,node.js,httpresponse,Node.js,Httpresponse,我已经创建了一个web服务器,它通过启动ls-l来显示目录和文件列表。由于我是node.js环境的新手,我不知道如何结束异步代码的HTTP正文响应。 下面是我的代码- var terminal = require('child_process').spawn('bash'); var http = require('http'); var s = http.createServer(function (req, res) { res.writeHead(200, {'content-t

我已经创建了一个web服务器,它通过启动ls-l来显示目录和文件列表。由于我是node.js环境的新手,我不知道如何结束异步代码的HTTP正文响应。 下面是我的代码-

var terminal = require('child_process').spawn('bash');
var http = require('http');
var s = http.createServer(function (req, res) {

    res.writeHead(200, {'content-type': 'text/plain'});
    terminal.stdout.on('data', function (data) {
        res.write('stdout: ' + data);
    });

    setTimeout(function () {
        res.write('Sending stdin to terminal');
        terminal.stdin.write('ls -l\n');
        res.write('Ending terminal session');
        terminal.stdin.end();
    }, 1000);

    terminal.on('exit', function (code) {
        res.write('child process exited with code ' + code + '\n');
        res.end("Response Ended");
    });
});
s.listen(8000);
这段代码可以很好地处理第一个请求。但在服务第二个请求时,有一个错误:“在结束后写入”。
为什么会这样?如何更正此问题?

您只能生成一个进程一次(在服务器启动之前),因此一旦该进程退出,您就不能再对其进行写入。请尝试以下方法:

var http = require('http'),
    spawn = require('child_process').spawn;
var s = http.createServer(function (req, res) {

    var terminal = spawn('bash');

    res.writeHead(200, {'content-type': 'text/plain'});
    terminal.stdout.on('data', function (data) {
        res.write('stdout: ' + data);
    });

    setTimeout(function () {
        res.write('Sending stdin to terminal');
        terminal.stdin.write('ls -l\n');
        res.write('Ending terminal session');
        terminal.stdin.end();
    }, 1000);

    terminal.on('exit', function (code) {
        res.write('child process exited with code ' + code + '\n');
        res.end("Response Ended");
    });
});
s.listen(8000);

您只能生成一个进程一次(在服务器启动之前),因此一旦该进程退出,您就不能再对其进行写入。请尝试以下方法:

var http = require('http'),
    spawn = require('child_process').spawn;
var s = http.createServer(function (req, res) {

    var terminal = spawn('bash');

    res.writeHead(200, {'content-type': 'text/plain'});
    terminal.stdout.on('data', function (data) {
        res.write('stdout: ' + data);
    });

    setTimeout(function () {
        res.write('Sending stdin to terminal');
        terminal.stdin.write('ls -l\n');
        res.write('Ending terminal session');
        terminal.stdin.end();
    }, 1000);

    terminal.on('exit', function (code) {
        res.write('child process exited with code ' + code + '\n');
        res.end("Response Ended");
    });
});
s.listen(8000);

如果你不想重新发明轮子,你应该看看连接和/或。顺便说一句,你应该格式化你的代码以便我们阅读。如果你不想重新发明轮子,你应该看看连接和/或。顺便说一句,你应该格式化你的代码,这样我们就可以阅读它。