Node.JS - 读取.html文件并向其写入用户输入

时间:2012-07-25 00:28:59

标签: node.js

我试图理解我是否可以获取节点来读取html文件(test.html),然后通过文本输入异步地将用户输入写入同一文件。 我在webserver.js上设置了我的Web服务器,然后设置了另一个名为test.html的页面。

我在交换机中添加了'test'案例的监听器,监听数据,将数据记录到服务器终端,然后(我假设)将这些数据写入文件。

据我所知,webserver.js脚本与test.html上的输入字段没有直接连接,这可能是我的第一个问题。 其次,我知道test.html上没有定义区域来呈现响应。 这是我想知道如何在Node中做的事情。

所以我希望我能得到一些关于如何让它发挥作用的指导,如果不是太麻烦的话。

var http = require('http')
, url = require('url')
, fs = require('fs')
, server;

server = http.createServer(function(req, res){

    var path = url.parse(req.url).pathname;

    var userData = "";

    switch(path){

      case '/':
        fs.readFile(__dirname + '/index.html', function (err, data) {
          if (err) throw err;
          res.writeHead(200, {'Content-Type': 'text/html'});
          res.write(data, 'utf8');
          res.end();
        });

      case '/test':
        fs.readFile(__dirname + '/test.html', function (err, data) {
          if (err) throw err;
          res.writeHead(200, {'Content-Type': 'text/html'});
          res.write(data, 'utf8');

          req.addListener("data", function(userDataChunk) {
              userData += userDataChunk;
              console.log("Received chunk ’"+userDataChunk + "’.");
              res.end("<p>" + userData + "</p>");
           });

      });

      break;

      default: '/';
  }
});

在test.html上我只有一个文本输入

<html>
  <head></head>
  <body>
    <input type="text" name="userInput" />
  </body>
</html>

我知道我可以在test.html上添加一些javascript以获取keyup上的输入并将其写入页面,但我只是想知道这是否可以用Node.js完成?

感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:1)

你必须将文本字段返回给服务器,这就是表单的作用。

<html>
  <head></head>
  <body>
    <form action="/test">
      <input type="text" name="userInput" />
      <input type="submit" />
    </form>
  </body>
</html>

现在要将内容实际写入html文件,您必须使用node.js标准库中的fs module