title: Node.js
date: 2019-09-01 14:27:58
tags: 后端
categories: # 这里写的分类会自动汇集到 categories 页面上,分类可以多级
node.js
基础
简易版 node-server
1 2 3 4 5 6 7 8 9 10 11 12 13
| var http = require("http"); var server = http.createServer(function (request, response) { response.setHeader("Content-Type", "text/plain; chartset=gbk"); response.writeHead(200, "ok"); response.write("hello"); response.end(); });
server.listen(9000);
console.log("open http://localhost:9000");
|
在终端中输入node index.js
就启动服务器.
简单版服务器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| var http = require("http");
var fs = require("fs");
var server = http.createServer(function (req, res) { console.log(__dirname + "/static" + req.url); var fileContent = fs.readFileSync(__dirname + "/static" + req.url, "binary"); res.write(fileContent, "binary"); res.end(); });
server.listen(8080); console.log("visit localhost:8080");
|
进阶
静态服务器.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| var http = require("http") var path = require("path") var fs = require("fs") var url = require("url")
function staticRoot(staticPath, req, res){ var pathObj = url.parse(req.url, true) console.log(pathObj)
if(pathObj.pathname === "/"){ pathObj.pathname += "index.html" }
var filePath = path.join(staticPath, pathObj.pathname)
fs.readFile(filePath, "binary", function(err, fileContent){ if(err){ res.writeHead(404, "not found") res.end("<h1>404 Not Found</h1>") }else{ res.writeHead(200, "ok") res.write(fileContent, "binary") res.end() } })
console.log("path.join(_dirname, "static")
var server = http.createServer(function(res,req){ staticRoot(path.join(__dirname, "static"), req, res) //__dirname代表当前文件路径,join拼接上static路径 })
server.listen(8080) console.log("visit http:
|
mock 数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| var http = require("http"); var fs = require("fs"); var url = require("url");
http .createServer(function (req, res) { var pathObj = url.parse(req.url, true);
switch (pathObj.pathname) { case "/getWeather": res.end(JSON.stringify({ a: 1, b: 2 })); break; case "user/123": res.end(fs.readFileSync(__dirname + "/static/user.tpl")); break; default: res.end(fs.readFileSync(__dirname + "static" + req.url)); } }) .listen(8080);
|
问题
__dirname
是什么
__dirname
总是指向被执行文件的绝对路径.
如/d1/d2/my.js
中的__dirname
,他的值就是/d1/d2
.
常用 API
fs.readFile(path[,options],callback)/fs.writeFile(file,data[,options],callback)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| let fs = require("fs");
fs.readFile("flie.txt", "utf-8", function (err, str) { if (err) { console.log("error"); } else { console.log(str); const strAfter = str.replace(/\d/gm, ""); console.log(strAfter);
fs.writeFile("fileAfter.txt", strAfter, (err) => { if (err) throw err; console.log("the file has been save!"); }); } });
|
模块
将上面的去数字的方法封装成函数,单独写一个文件,并调用
创建stringApi.js
1 2 3 4 5 6
| function replaceDigit(str) { return str.replace(/\d/gm, ""); }
module.exports.replaceDigit = replaceDigit;
|
1 2 3 4 5 6
|
let strApi = require("./stringApi");
const strAfter = strApi.replaceDigit(str);
|
NPM
如果需要一些功能,node.js 自带的没有,可以去 npm 官网上找一些其他人发布的 npm 包.
找到之后,首先进行安装
package.json
记录保存模块依赖,当没有依赖时,比如下载其他人的项目里没有依赖,可以使用npm.init
初始化,将 package.json 中记录的模块依赖全都下载下来,方便.
npm 切换源工具
1 2 3 4
| npm install -g nrm nrm ls nrm use taobao nrm use npm
|
NPM Script
在 package.json 文件里有一个 scripts 对象,写入里面的命令可以比较方便快捷的执行.直接npm xxx
就可以执行.而且会自动搜索路径,不用写相对路径.
1 2 3 4 5 6 7 8 9 10 11 12
| { "scripts": { "css:autoprefixer": "postcss -u autoprefixer -r dist/css/*", "css:compress": "csso in.css --output out.css", "js:lint": "eslint src/js", "js:uglify": "mkdir -p dist/js && uglifyjs src/js/*.js -m -o dist/js/app.js", "image:imagemin": "app=imagemin-cli npm run check; imagemin src/images dist/images -p", "server": "browser-sync start --server --files 'dist/css/*.css, dist/js/*.js'", "watch": "onchange 'src/js/*.js' -- npm run css:compress", "start": "npm run server" } }
|
1 2
| npm run css:autoprefixer npm start
|