0

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

我在交换机的“测试”用例中添加了侦听器,以侦听数据,将数据记录到服务器终端,然后(我假设)将此数据写入文件。

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

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

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 完成?

任何帮助表示赞赏,谢谢。

4

1 回答 1

1

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

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

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

于 2012-07-25T00:58:09.513 回答