如何在node.js中结束HTTP响应主体

时间:2014-05-24 17:00:38

标签: node.js httpresponse

我创建了一个Web服务器,通过触发ls -l显示目录和文件列表。由于我是node.js环境的新手,我不知道如何结束异步代码的HTTP Body响应。 以下是我的代码 -

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);

此代码适用于提供第一个请求。但是在提供第二个请求时会出现错误:"写完后#34;。 为什么会这样?我怎么能纠正这个?

1 个答案:

答案 0 :(得分:3)

您只生成一次进程(在服务器启动之前),因此一旦该进程退出,您就不能再写入它了。试试这个:

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);