Node.js 笔记

NVM

官方文档

1
2
3
4
nvm install v12.18.3
nvm ls
nvm use v12.18.3
nvm alias default v12.18.3

MongoDB

官方文档

  • 安装路径

C:\Program Files\MongoDB\Server\4.0\bin

  • 启动 shell
1
mongo
  • 新建视图
1
db.createView("man","users",{$match:{sex:1}})
  • 导入
1
mongoimport --db users --collection contacts --file contacts.json --jsonArray
  • 导出
1
mongoexport --db users --collection contacts --out contacts-out.json --jsonArray --pretty
  • 备份
1
mongodump -h localhost -d users -o .
  • 恢复
1
mongorestore -h localhost -d users .

adminMongo

MongoDB Web 可视化工具

1
2
3
4
5
6
git clone https://github.com/mrvautin/adminMongo
cd adminMongo
npm install
npm start
http://127.0.0.1:1234 
mongodb://127.0.0.1:27017

nodemon

node.js 版本的 live-server

1
2
3
yarn global add nodemon
nodemon -h
nodemon ./server.js localhost 8080

pm2

node.js 进程管理器

 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
# 查看端口占用情况
netstat -ano
yarn global add pm2

# 启动 nodejs 服务器
pm2 start app.js --name node-server --watch

# 启动静态文件服务器
pm2 serve . 9003 --spa --name hugo-blog --watch

# 启动 Vue 项目
pm2 start "npm run dev" --name 805-app

# 启动 Caddy
pm2 start "caddy -conf /www/Caddyfile" --name caddy
pm2 start "caddy run -config ~/Caddyfile" --name caddy

pm2 start webhook --name webhook -- -hooks hooks.json -port 9091 -hotreload -verbose

pm2 start "python manage.py runserver 0.0.0.0:9082" --name python-wechat
pm2 start "sandman2ctl 'sqlite+pysqlite:///sandman2.db' -p 9080" --name python-sandman

# 查看pm2管理的应用运行状态
pm2 ls

# pm2 停止进程
pm2 stop ..
pm2 delete ..

# 开机自动启动已启动的服务
pm2 start ..
pm2 save
pm2 startup

# 删除自动启动服务
pm2 unstartup systemd

hotel

node.js 端口管理器

 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
yarn global add hotel && hotel start

http://localhost:2000/

# Use

hotel add <cmd|url> [opts]
hotel run <cmd> [opts]

# Examples

hotel add 'nodemon app.js' --out dev.log  # Set output file (default: none)
hotel add 'nodemon app.js' --name name    # Set custom name (default: current dir name)
hotel add 'nodemon app.js' --port 3000    # Set a fixed port (default: random port)
hotel add 'nodemon app.js' --env PATH     # Store PATH environment variable in server config
hotel add http://192.168.1.10 --name app  # map local domain to URL

hotel run 'nodemon app.js'                # Run server and get a temporary local domain

# Other commands

hotel ls     # List servers
hotel rm     # Remove server
hotel start  # Start hotel daemon
hotel stop   # Stop hotel daemon

json server

接口本地测试服务器

1
2
3
4
5
6
7
8
9
{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
yarn global add json-server
json-server --watch db.json --port 3000
json-server index.js
http://localhost:3000/posts/1

GET    /posts
GET    /posts/1
POST   /posts
PUT    /posts/1
PATCH  /posts/1
DELETE /posts/1

Mock.js

官方文档

模拟数据工具

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
id: i,
user_id: Random.id(),
detail: Random.csentence(5, 30),
thumb: Random.dataImage('64x64', 'mock'),
email: Random.email(),
address: Random.county(true),
title: Random.cword(8,20),
city: Random.city(),
name: Random.cname(),
date: Random.date(),
desc: content.substr(0,40),
tag: Random.cword(2,6),
views: Random.integer(100,5000),
images: images.slice(0,Random.integer(1,3))

adonis

类 laravel 的 node.js 框架

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
yarn global add adonis-cli
adonis new blog
cd blog
npm run serve:dev
node ace
node ace make:controller User --resource
node ace make:model User
node ace make:migration users --create=users
node ace migration:run
node ace migration:status
node ace make:seed User

fastify-cli

node.js 高性能框架

1
2
3
4
5
6
# 全局安装
yarn global add fastify-cli
fastify generate

# 项目引入
yarn add fastify
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// Require the framework and instantiate it
const fastify = require('fastify')({
  logger: true
})
 
// Declare a route
fastify.get('/', (request, reply) => {
  reply.send({ hello: 'world' })
})
 
// Run the server!
fastify.listen(3000, (err, address) => {
  if (err) throw err
  fastify.log.info(`server listening on ${address}`)
})

sails

类 ruby on rails 的 node.js 框架

1
2
3
4
5
yarn global add sails
sails new sails-api --no-front-end --fast
cd sails-api
sails generate api test
sails lift

To use MongoDB in your Node.js/Sails app during development:

  1. Run npm install sails-mongo in your app folder.

  2. In your config/datastores.js file, edit the default datastore configuration:

    1
    2
    3
    4
    
    default: {
       adapter: 'sails-mongo',
       url: 'mongodb://root@localhost/foo'
     }
    
  3. In your config/models.js file, edit the default id attribute to have the appropriate type and columnName for MongoDB’s primary keys:

    1
    2
    3
    4
    
    attributes: {
       id: { type: 'string', columnName: '_id' },
       //...
     }
    

That’s it! Lift your app again and you should be good to go.

RouteBlueprint ActionExample URL
GET /:modelIdentity/findfindhttp://localhost:1337/user/find?name=bob
GET /:modelIdentity/find/:idfindOnehttp://localhost:1337/user/find/123
GET /:modelIdentity/createcreatehttp://localhost:1337/user/create?name=bob&age=18
GET /:modelIdentity/update/:idupdatehttp://localhost:1337/user/update/123?name=joe
GET /:modelIdentity/destroy/:iddestroyhttp://localhost:1337/user/destroy/123
GET /:modelIdentity/:id/:association/add/:fkaddhttp://localhost:1337/user/123/pets/add/3
GET /:modelIdentity/:id/:association/remove/:fkremovehttp://localhost:1337/user/123/pets/remove/3
GET /:modelIdentity/:id/:association/replace?association=[1,2…]replacehttp://localhost:1337/user/123/pets/replace?pets=[3,4]

Nest.js

Nest 是一个用于构建高效,可扩展的 Node.js 服务器端应用程序的框架

1
2
3
4
yarn global add @nestjs/cli
nest new project-name
cd project-name
npm run start

main.ts

1
2
3
4
5
6
7
8
import { NestFactory } from '@nestjs/core';
import { ApplicationModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(ApplicationModule);
  await app.listen(3000);
}
bootstrap();