据Node官网介绍(事实也是如此)
Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境。
Node.js 使用了一个事件驱动、非阻塞式 I/O 的模型,使其轻量又高效。
那么实际项目中我们可以利用node干些什么呢?
读写文件
http服务器
网络服务的构建
网络通信
操作数据库
模板引擎的渲染。。。
一、安装:
地址:https://nodejs.org/en/
选择对应的电脑系统直接下载,然后下一步下一步的安装就行。
安装完 cmd 执行 node -v 检测版本号
二、搭建服务器
原生node有提供很多核心模块,搭建起来了也很简单。
运行:node app.js (app.js为node的文件名)
const http = require("http"); //加载http核心模块
const server = http.createServer(); //创建web服务器
server.on('request',function () { //接受客户端请求
console.log('接受客户端请求')
})
server.listen(3000,function(req,res){ //绑定端口,监听启动服务
console.log(`web服务器 3000已经启动`)
})
*************************或者**************************************
const http = require("http"); //加载http核心模块
const server = http.createServer(); //创建web服务器
http
.createServer(function(req, res) {
console.log('接受客户端请求')
})
.listen(3000, function() { //绑定端口,监听启动服务
console.log(`web服务器 3000已经启动`);
});
三、搭建路由
const http = require("http"); //加载http核心模块
const allurl = require("url"); //
const server = http.createServer(); //创建web服务器
server.on('request',function (req, res) { //接受客户端请求
let parseObj = allurl.parse(req.url, true);// url.parse 参数转成对象 true
let url = parseObj.pathname;//单独获取?前面的url参数路径
if (url === "/") {
res.end(
{code:200,
message:'成功',
data:{
total:10,
list:[]}
});
} else if (url === "/list") {
res.end(url);
}else{
res.end(url);
}
console.log('接受客户端请求')
res.end()
})
server.listen(3000,function(){ //绑定端口,监听启动服务
console.log(`web服务器 3000已经启动`)
})
四、文件处理
对文件的处理需要用到 fs和path这两个核心模块
const http = require("http"); //加载http核心模块
const allurl = require("url");
const fs = require("fs");
const path = require("path");
const server = http.createServer(); //创建web服务器
const views = path.join(__dirname, "views"); //指向当前目录下的views文件夹
server.on('request',function (req, res) { //接受客户端请求
let parseObj = allurl.parse(req.url, true);// url.parse 参数转成对象 true
let url = parseObj.pathname;//单独获取?前面的url参数路径
if (url === "/") {
fs.readFile(path.join(views, "view.html"), function(err, data) {
if (err) {
return res.end("找不到渲染文件");
}
//将views文件下的view.html读取出来,以字符串形式返回到客户端
res.end(data.toString());
});
} else if (url === "/list") {
fs.writeFile(
path.join(views, "write.md"),
'第一次写入内容',
function(err, data) {
if (err) {
return res.end("找不到渲染文件");
}
//写入成功给客户端返回信息
res.end('文件写入成功');
});
}else{
res.end(url);
}
console.log('接受客户端请求')
res.end()
})
server.listen(3000,function(){ //绑定端口,监听启动服务
console.log(`web服务器 3000已经启动`)
})
参考了:node官网