Node.JS 是一个基于 Chrome V8 引擎的 JavaScript 运行环境. Node.JS 使用了一个事件驱动, 非阻塞式 I/O 的模型.
Node.JS 打开 html 页面的方法:
使用 fs 模块提供的 readFile 方法打开文件, 让其以 text/HTML 的形式输出.
代码:
- var express = require('express');
- var fs=require("fs");
- var App = express();
- // 方法 1: 通过 express.static 访问静态文件, 这里访问的是 Ajax.HTML
- // App.use(express.static("./"));
- // 方法 2: 使用 fs.readFile 打开 HTML 文件
- App.get("/helloworld.html", function(request, response) {
- fs.readFile("./"+request.path.substr(1),function(err,data){
- // body
- if(err){
- console.log(err);
- //404:NOT FOUND
- response.writeHead(404,{"Content-Type":"text/html"});
- }
- else{
- //200:OK
- response.writeHead(200,{"Content-Type":"text/html"});
- response.write(data.toString());
- }
- response.end();
- });
- });
- App.listen(3000, function() { // 监听 http://127.0.0.1:3000 端口
- console.log("server start");
- });
浏览器访问, 输入 http://127.0.0.1:3000/hello_fs.html
结果如下:
来源: http://www.css88.com/qa/node-js/10801.html