Node.js初学者 - 无法通过节点教程 2 - 标准输出和子进程



我试图通过教程 nodetuts.com - 教程 2,不幸的是无法让示例工作,我对 node 很陌生.js并且正在浏览任何我可以掌握的教程。我知道node.js仍然是测试版,我认为使这项工作的代码现在已经过时了。(这是代码):

var http = require('http');
var spawn  = require('child_process').spawn;
http.createServer(function(request, response){
    response.writeHead(200, {
        'Content-Type' : 'text/plain'
    });
    var tail_child = spawn('tail', ['-f', 'test.txt']);
    tail_child.stdout.on('data', function(data){
        console.log(data.toString());
        response.write(data);
    });

}).listen(4000);

无论如何,决心继续下去,我一直在浏览节点网站上的文档,发现: http://nodejs.org/api/all.html#all_child_pid 这不是我想要的(我想完成链接到顶部的教程),但我想与子进程工作有关,并将该代码合并到其中:

var http = require('http');
var server = http.createServer(function(res, req){
    res.writeHead(200);
    res.end('testing');

    var spawn = require('child_process').spawn,
        grep  = spawn('grep', ['ssh']);
    console.log('Spawned child pid: ' + grep.pid);
    grep.stdin.end();
}).listen(4000);

不幸的是,当我刷新页面时http://localhost:4000/我什么也得不到,命令提示符吐出:(我知道它说 writeHead 是一个问题,但它在其他示例中工作正常 - (如 nodetuts - 教程 1))

        res.writeHead(200);
            ^
TypeError: Object #<IncomingMessage> has no method 'writeHead'
    at Server.<anonymous> (Z:Joseph Goss FolderGoogle DriveCodejavascript_firstnodejs_firststdoutTest.js:20:6)
    at Server.EventEmitter.emit (events.js:91:17)
    at HTTPParser.parser.onIncoming (http.js:1785:12)
    at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:111:23)
    at Socket.socket.ondata (http.js:1682:22)
    at TCP.onread (net.js:404:27)

想知道为什么我不能让它工作,我显然错过了一些东西,但我不知道是什么,我什至无法通过教程 2。 :(

  • 我正在运行窗口 7
  • 我还看过这段代码,为什么 response.write 似乎在 Node.js 中阻止了我的浏览器?而他的代码也根本不起作用。

您在传递给createServer的函数中交换了reqres

var http = require('http');
var server = http.createServer(function(req, res){
    res.writeHead(200);
    res.end('testing');

    var spawn = require('child_process').spawn,
        grep  = spawn('grep', ['ssh']);
    console.log('Spawned child pid: ' + grep.pid);
    grep.stdin.end();
}).listen(4000);

最新更新