如何在nodejs中获取HTML页面?

时间:2013-04-18 01:14:07

标签: html node.js

的test.html

<html>
    <head>
        <title>Test Page</title>
    </head>
    <body> This is the body</body>
</html>

我该如何修改:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

返回上面的 test.html

1 个答案:

答案 0 :(得分:1)

以下是简单流式静态服务器的示例

var basepath = '/files'

http.createServer(function (req, res) {
  if (req.method !== 'GET') {
    res.writeHead(400);
    res.end();
    return;
  }
  var s = fs.createReadStream(path.join(basepath, req.path));
  s.on('error', function () {
    res.writeHead(404);
    res.end();
  });
  s.once('fd', function () {
    res.writeHead(200);
  });
  s.pipe(res);
});

在练习中你应该使用express.static:http://runnable.com/UWw3g0PKxoAWAA6K

或像https://github.com/jesusabdullah/node-ecstatic

这样的deticated静态模块