node小记

185 阅读3分钟

安装

官网下载安装包 [node官网](https://nodejs.org/cn/)

启动

node -v 查看版本号
node 文件名.js node启动这个文件

http模块

app.js

var http = require("http");  // 引入核心模块http
var server = http.createServer(); // 添加一个请求服务

// 处理请求信息
server.on("request", function (req, res) {
    res.end(req.url);
});

// 监听端口号
server.listen("3030", function () {
    console.log("启动了");
});

path模块

var path = require('path');

node项目中,文件的相对路径是根据node的启动位置匹配的,在不同的路径下启动node服务,会造成静态资源加载不到的情况,所以需要设置文件的绝对路径.
_dirname node的全局模块, 获取文件夹的文件绝对路径
通过设置/node_modules的文件路径,node会在前面自动拼接文件所在项目的绝对文件地址,避免启动项目,文件无法加载的情况
app.use(
    "/node_modules",
    express.static(path.join(__dirname, "./node_modules"))
);

express框架

[中文文档](https://www.expressjs.com.cn/starter/installing.html)

安装
cnpm i express

引入
var express = require("express");

使用
var app = express();
// get请求
aap.get('/', function (req, res) {
    res.send(req.url)
})
// post请求 需要引入express中间件 body-parser
var bodyParser = require('body-parser');
aap.post('/', function (req, res) {
    console.log(req.body);
    res.send(req.body)
})
res.send("内容")  // 会在当前请求页面上生成内容
res.status(200).json("内容") // ajax请求数据返回json内容

// 解析json
app.use(bodyParser.json()); 
// 解析form-data
app.use(bodyParser.urlencoded());
// 开启监听
app.listen("3000");

art-template 模板引擎

[文档](http://aui.github.io/art-template/zh-cn/docs/installation.html)

安装
cnpm i art-template -S
cnpm i express-art-template -S // express中使用需要安装

使用
var express = require("express");
var app = express();

// 在express中使用,直接引入express-art-template即可,它依赖于art-template
app.engine("html", require("express-art-template"));
app.set("views", path.join(__dirname, "views"))

app.get("/", function (req, res) {
    res.render("index.html", {
        header: "wiven编程笔记",
        notes: [
            title: "node小记",
            src: 'https://juejin.im/editor/drafts/5f057a145188252e3a45d31d'
        ]
    });
});

views/index.html

<title>{{header}}</title>

<ul>
    {{each notes}}
    <li>
        <a target="_blank" href="{{$value.src}}">{{$value.title}}</a>
    </li>
    {{/each}}
</ul>

mongoDB 数据库

本地安装
# 进入 /usr/local
cd /usr/local

# 下载
sudo curl -O https://fastdl.mongodb.org/osx/mongodb-osx-ssl-x86_64-4.0.9.tgz

# 解压
sudo tar -zxvf mongodb-osx-ssl-x86_64-4.0.9.tgz

# 重命名为 mongodb 目录

sudo mv mongodb-osx-x86_64-4.0.9/ mongodb

# 创建数据库目录
sudo mkdir -p /data/db

如果无法在根目录创建文件
1 在非根目录创建数据库data文件 /usr/local/data/bin
2 重启电脑 按住command + r进入恢复模式
3 打开终端 输入csrutil disable 重启
4 ln -s /usr/local/data /data  // 会将两个data目录进行软连接
或者在其它目录川建好文件夹 /usr/local/data/db
在mongodb/bin打开终端输入: sudo ./mongod --dbpath /usr/local/data/db
后面如果允许sudo mongod提示NonExistentPath: Data directory /data/db not found以及mongodb shutting down with code:100,是因为映射的data/db文件未找到,再执行sudo ./mongod --dbpath /usr/local/data/db即可

# 配置全局mongod命令
vi ~/.bash_profile
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
export PATH=/usr/local/mongodb/bin:$PATH
source ~./bash_profile  启用生效
如果后续启用mongod命令提示connot,则需要配置zshrc环境变量
vi ~/.zshrc
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
export PATH=/usr/local/mongodb/bin:$PATH
source ~./bash_profile
source ~./bash_profile  启用生效

启动
sudo mongod
新开一个终端在mongodb/bin下 ./mongod 启动mongodb控制台

服务器安装
1. sudo vim /etc/yum.repos.d/mongodb-enterprise-4.2.repo
2. 输入:
[mongodb-enterprise-4.2]
name=MongoDB Enterprise Repository
baseurl=https://repo.mongodb.com/yum/redhat/$releasever/mongodb-enterprise/4.2/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.2.asc
:wq
3. sudo yum install -y mongodb-enterprise
4. 修改配置: 
sudo vi /etc/mongod.conf
bind_ip = 127.0.0.1 改为bind_ip=0.0.0.0
5. sudo service mongod start 启动

开发使用
app.js

var express = require("express");
var path = require("path");
var bodyParser = require('body-parser');
var router = require("./router");
var app = express();

app.engine("html", require("express-art-template"));
app.set("views", path.join(__dirname, "views"));
app.use(
    "/node_modules",
    express.static(path.join(__dirname, "./node_modules"))
);

// 解析json
app.use(bodyParser.json());
// // 解析form-data
app.use(bodyParser.urlencoded());
// 使用router
app.use(router);
app.listen("3000");


router.js
var express = require("express");
var router = express.Router();
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/notes");

var noteSchema = mongoose.Schema({
    title: String,
    src: String,
});
var note = mongoose.model("note", noteSchema);

var mynote = new note({
    title: "nuxt使用小结",
    src: "https://juejin.cn/post/6844903857277894664",
});
mynote.save(function (err, data) {
    if (err) return console.log(err, "saveerr");
    note.find(function (err, data) {
        if (err) return console.log(err, "finderr");
        console.log(data, "notedata");
    });
});
note.remove({ _id: "5f044993b2cb114dff66162f" }, function (err, data) {
    if (err) return console.log(err, "removeDel");
    console.log(data, "delok");
});

router.get("/", function (req, res) {
    note.find(function (err, data) {
        if (err) return console.log(err, "finderr");
        res.render("index.html", {
            header: "wiven编程笔记",
            notes: data,
        });
    });
});

router.get("/notes", function (req, res) {
    note.find(function (err, data) {
        if (err) return console.log(err, "finderr");
        res.status(200).json({
            code: 200,
            data: data,
        });
    });
});

router.post("/notes", function (req, res) {
    res.status(200).json({
        code: 200,
        data: req.body,
    });
});

module.exports = router;