官方介绍
Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.
Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境。
Node.js 使用了一个事件驱动、非阻塞式 I/O 的模型,使其轻量又高效。
Node.js 的包管理器 npm,是全球最大的开源库生态系统。
runtime 运行时(运行环境)
PHP代码要想运行需要借助于Apache这个服务器(运行时,运行环境)
JavaScript代码想要运行:需要有一个JavaScript的运行时即可
在web端,浏览器就可以看作JS的运行时
在Node端,Node就是JS的运行时
安装node
- 下载地址
- 官网术语解释
- LTS 版本:Long-term Support 版本,长期支持版,即稳定版。
- Current 版本:Latest Features 版本,最新版本,新特性会在该版本中最先加入。
- 验证是否安装成功:在终端输入
node -v
,如果打印出版本号,即安装成功
读取文件和写入文件操作
// 引包
var fs = require('fs')
// readFile() 读取文件API
fs.readFile(filename,[encoding],[callback(err,data)]);
-filename(必选),表示要读取的文件名。
-encoding(可选),表示文件的字符编码。
-callback 是回调函数,用于接收文件的内容。
//如果第二个参数不传,则data是buffer数据读取的时候需要data.toString()
- 写入
fs.writeFile(filename,data,[options],callback)--写入的数据会覆盖原有的数据,如果要追加数据则需要读取数据在添加 - filename(必选),表示要写入的文件路径。
-data(必选),写入的数据 - options(可选),表示文件的字符编码。
- callback 是回调函数,用于接收文件的内容。
模拟服务器
1.首先需要初始化包管理仓库,npm init -y
2.安装依赖项,npm i mime -s
i. 项目目录
web文件夹内是一个静态页面文件以及文件内需要的其他资源文件

const http = require("http");
const fs = require("fs");
const mime = require("mime");
const path = require("path");
//除了mime需要自己安装,其他的http,fs,path都是核心模块,是node中自带的模块,不需要我们再引入依赖项
const server = http.createServer();
server.on("request", function (req,res) {
let url = req.url;
if (url === "/") {
fs.readFile(path.join(__dirname, "web", "index.html"), 'utf8',function (err, data) {
if (err) {
res.statusCode = 404;
res.statusMessage = 'Not Found'
res.end()
return
}
res.setHeader('Content-Type', 'text/html')
res.end(data);
})
} else {
// 获取文件类型
let mineType = mime.getType(url);
// 这里不能使用utf8编码读取文件,因为文件中有图片,读取以后图片会不展示
fs.readFile(path.join(__dirname, "./web", url), (err,data) => {
if (err) {
res.statusCode = 404;
res.statusMessage = 'Not Found'
res.end()
return
}
res.writeHead(200, {
'Content-Type': mineType
})
res.end(data);
})
}
})
//监听3000端口
server.listen(3000,function () {
console.log("项目开启:http://localhost:3000/")
})
启动node app.js,并打开localhost:3000则打开了我们的文件了。
网友评论