笔记-Node.js createServer & Node.js path

Node.js createServer

//appp.jsconst http = require("http"); //载入node.js 模组http   .createServer(function (request, response) {    if (request.url == "/") {      //if网址输入127.0.0.1:9527      response.writeHead(200, { "Content-Type": "text/plain" }); //回传给user的文字格式      response.write("Hi, World!");      response.end(); //回应中止    } else if (request.url == "/test") {      //if网址输入127.0.0.1:9527/test      response.writeHead(200, { "Content-Type": "text/html" });      response.write("<h2>New page!</h2>");      response.end();    } else {      response.writeHead(200, { "Content-Type": "text/html" });      response.write("<h2>No Pages here.</h2>");      response.end();    }  })  .listen(9527);
.listen(9527)也可写成server.listen(9527) //执行node appp.js后 在浏览器网址列打127.0.0.1:9527 即可回传write中的内容 (127.0.0.1为本地主机,9527为port,注意有些port有固定用途)//也可将plain改成html后于write中补上html tag 範例如下
response.writeHead(200, { "Content-Type": "text/html" });    response.write("<html><body>Hi, World!</body></html>");

载入 const path = require('path'); 可用以下语法

- 抓目录路径: path.dirname('/aa/bb/cc.js') 回传 /aa/bb- 抓档名: path.basename('/aa/bb/cc.js') 回传 cc.js- 抓副档名: path.extname('/aa/bb/cc.js') 回传 js- 分析路径: path.parse('/aa/bb/cc.js') 回传 上述所有物件- 路径合併:path.join(__dirname,'/aa') 回传 前后路径合併 ex: const pathTest = path.join("C", "Users", "Administrator", "..", "Users"); console.log(pathTest); //C\Users\Users (注: ".."是往前退一层)

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章