Node.js生成html [英] Node.js Generate html

查看:99
本文介绍了Node.js生成html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个生成数据列表的JavaScript程序。示例输出如下:

I have created a JavaScript program which generates a list of data. Example output below:

output one 
output two 
output three 
...

我希望能够生成一个可以保存到磁盘并用浏览器打开的HTML文件。以下是我想要生成的HTML样本。

I would like to be able to generate a HTML file which can be saved to disk and opened with a browser. Below is a sample of the HTML I would like to generate.

<html>
    <head>
    </head>
    <body>
        <table id="history_table">
            <tr>
                <td>header 1</td>
                <td>header 2</td>
                <td>header 3</td>
            </tr>
            <tr>
               <td>output one</td>
            </tr>
            ...
        </table>
    </body>
</html>

我试过这样做:

I have tried doing this:

var htmlDoc = document.createElement("HMTL");
htmlDoc.innerhtml('<head></head><body>...</body>');

但是这显然是错误的,因为文档对象不存在。

But this is clearly wrong since the document object does not exist.

推荐答案

Node.js不在浏览器中运行,因此您不会有文档对象可用。实际上,你甚至不会有DOM树。如果您在这一点上有点困惑,我鼓励您阅读更多

Node.js does not run in a browser, therefore you will not have a document object available. Actually, you will not even have a DOM tree at all. If you are a bit confused at this point, I encourage you to read more about it before going further.

有几种方法可以选择做你想做的事。

There are a few methods you can choose from to do what you want.

因为你写过关于在浏览器中打开文件,为什么不使用一个将直接作为HTTP服务来提供文件的框架,而不是两步过程?这样,你的代码将变得更加动态和易于维护(不会提到你的HTML总是最新的)。

Because you wrote about opening the file in the browser, why don't you use a framework that will serve the file directly as an HTTP service, instead of having a two-step process? This way, your code will be more dynamic and easily maintainable (not mentioning your HTML always up-to-date).

这里有很多框架:

  • Http (Node native API)
  • Connect
  • koa
  • Express (using Connect)
  • Sails (build on Express)
  • Geddy
  • CompoundJS
  • etc.

你可以做的最基本的方式就是这样:

The most basic way you could do what you want is this :

var http = require('http');

http.createServer(function (req, res) {
  var html = buildHtml(req);

  res.writeHead(200, {
    'Content-Type': 'text/html',
    'Content-Length': html.length,
    'Expires': new Date().toUTCString()
  });
  res.end(html);
}).listen(8080);

function buildHtml(req) {
  var header = '';
  var body = '';

  // concatenate header string
  // concatenate body string

  return '<!DOCTYPE html>'
       + '<html><header>' + header + '</header><body>' + body + '</body></html>';
};

使用 http:// localhost:8080 您的浏览器。

编辑:你也可以用小的 HTTP

(Edit: you could also serve them with a small HTTP server.)

如果你想要做的只是生成一些HTML文件,那么简单一点。为了在文件系统上执行IO访问,Node为此提供了一个API,此处。 p>

If what you are trying to do is simply generating some HTML files, then go simple. To perform IO access on the file system, Node has an API for that, documented here.

var fs = require('fs');

var fileName = 'path/to/file';
var stream = fs.createWriteStream(fileName);

stream.once('open', function(fd) {
  var html = buildHtml();

  stream.end(html);
});

注意: buildHtml 函数完全与方法1 相同。

这是最基本的Node.js实现,需要调用的应用程序来处理输出本身。要在Node中输出一些东西(比如stdout),最好的方法是使用 console.log(message),其中 message 是任何字符串或对象等。

This is the most basic Node.js implementation and requires the invoking application to handle the output itself. To output something in Node (ie. to stdout), the best way is to use console.log(message) where message is any string, or object, etc.

var html = buildHtml();

console.log(html);

注意: buildHtml 函数完全与方法1 相同(再次)

Note: The buildHtml function is exactly the same as in Method 1 (again)

如果脚本名为 html-generator.js (例如),在基于Linux / Unix的系统中,只需执行

If your script is called html-generator.js (for example), in Linux/Unix based system, simply do

$ node html-generator.js > path/to/file






结论



因为Node是一个模块化系统,所以您甚至可以将 buildHtml 函数放入它自己的模块中,只需编写适配器来处理HTML不过你喜欢。就像


Conclusion

Because Node is a modular system, you can even put the buildHtml function inside it's own module and simply write adapters to handle the HTML however you like. Something like

var htmlBuilder = require('path/to/html-builder-module');

var html = htmlBuilder(options);
...

您必须考虑服务器端而不是客户端 - 边写为Node.js写JavaScript;你不是在浏览器和/或仅限于沙箱,除了V8引擎。

You have to think "server-side" and not "client-side" when writing JavaScript for Node.js; you are not in a browser and/or limited to a sandbox, other than the V8 engine.

额外阅读,了解 npm 。希望这有助于。

Extra reading, learn about npm. Hope this helps.

这篇关于Node.js生成html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆