Node.js专题nodejs我爱编程

干货 | Node.js有用的功能组件

2017-07-14  本文已影响168人  Mike的读书季

1.数据库操作

1.1 mongoose

mongoose是一款Node.js便捷操作MongoDB的对象模型工具。

mongoose

安装

npm install mongoose

简单使用(摘自官网)

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

var Cat = mongoose.model('Cat', { name: String });

var kitty = new Cat({ name: 'Zildjian' });
kitty.save(function (err) {
  if (err) {
    console.log(err);
  } else {
    console.log('meow');
  }
});

注意:需要先运行 MongoDB 服务


官网资料

MongoDB: https://www.mongodb.com/
Mongoose: http://mongoosejs.com/


关于如何使用MongoDB和Mongoose,欢迎阅读我的文章:

MongoDB基础0——MongoDB的安装与可视化管理工具
MongoDB基础1——数据库基本操作
MongoDB基础2——Mongoose的操作指南
MongoDB基础3——Mongoose的数据交互问题
MongoDB基础4——安全与身份认证
MongoDB基础X——踩过的坑以及解决方案(持续更新中)


1.2 redis

Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件。 它支持多种类型的数据结构,如 字符串(strings), 散列(hashes), 列表(lists), 集合(sets), 有序集合(sorted sets) 与范围查询, bitmaps, hyperloglogs 和 地理空间(geospatial) 索引半径查询。 Redis 内置了 复制(replication),LUA脚本(Lua scripting), LRU驱动事件(LRU eviction),事务(transactions) 和不同级别的 磁盘持久化(persistence), 并通过 Redis哨兵(Sentinel)和自动 分区(Cluster)提供高可用性(high availability)。

资料来源 - Redis 中文官网: http://www.redis.cn/


这里所说的redis是Node.js对redis数据库进行操作的一个中间件。


安装

npm install redis --save

简单使用(摘自官网)

var redis = require("redis"),
    client = redis.createClient();

// if you'd like to select database 3, instead of 0 (default), call
// client.select(3, function() { /* ... */ });

client.on("error", function (err) {
    console.log("Error " + err);
});

client.set("string key", "string val", redis.print);
client.hset("hash key", "hashtest 1", "some value", redis.print);
client.hset(["hash key", "hashtest 2", "some other value"], redis.print);
client.hkeys("hash key", function (err, replies) {
    console.log(replies.length + " replies:");
    replies.forEach(function (reply, i) {
        console.log("    " + i + ": " + reply);
    });
    client.quit();
});

github: https://github.com/NodeRedis/node_redis
npm: https://www.npmjs.com/package/redis


关于redis在Node.js中的应用,可阅读我的文章:
《Node.js的Redis简单例子》


1.2 mysql

A pure node.js JavaScript Client implementing the MySql protocol.


安装

npm install mysql

简单使用(摘自官网)

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'me',
  password : 'secret',
  database : 'my_db'
});

connection.connect();

connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
  if (error) throw error;
  console.log('The solution is: ', results[0].solution);
});

connection.end();

Github地址: https://github.com/mysqljs/mysql


2.网络

2.1 http-proxy

安装

npm install http-proxy --save

简单使用(摘自官网)

var http = require('http'),
    httpProxy = require('http-proxy');

//
// Create a proxy server with custom application logic
//
var proxy = httpProxy.createProxyServer({});

//
// Create your custom server and just call `proxy.web()` to proxy
// a web request to the target passed in the options
// also you can use `proxy.ws()` to proxy a websockets request
//
var server = http.createServer(function(req, res) {
  // You can define here your custom logic to handle the request
  // and then proxy the request.
  proxy.web(req, res, { target: 'http://127.0.0.1:5060' });
});

console.log("listening on port 5050")
server.listen(5050);

github: https://github.com/nodejitsu/node-http-proxy


欢迎阅读我的文章:
《http-proxy反向代理以调度服务器各app》


2.2 request

request是node.js的一个中间件,用它可以通过服务器请求url并返回数据。

request可以作为Node.js爬虫爬取网络资源的工具,也可以使用它来实现oAuth登录。

更多资料,可参考:《Request —— 让 Node.js http请求变得超简单》


安装

npm install request --save

简单使用(摘自官网)

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});

Github:https://github.com/request/request


2.3 cheerio

像jQuery操作网页一样在服务端操作抓取的网页数据:Fast, flexible & lean implementation of core jQuery designed specifically for the server.


安装

npm install cheerio --save

简单使用(摘自官网)

const cheerio = require('cheerio')
const $ = cheerio.load('<h2 class="title">Hello world</h2>')

$('h2.title').text('Hello there!')
$('h2').addClass('welcome')

$.html()
//=> <h2 class="title welcome">Hello there!</h2>

request的应用:
Node.js通过微信网页授权机制获取用户信息
卫星信息抓取工具SatCapturer


Github:https://github.com/cheeriojs/cheerio


3.发送邮件

3.1 Nodemailer

Nodemailer

Nodemailer 是一款Node.js用于发送邮件的中间件,您可以使用自己的邮箱帐户和密码,通过此中间件来发送邮件。

Nodemailer支持批量发送给多个邮箱,支持抄送和密送;此外,它还支持发送带附件的邮件。

Nodemailer遵循MIT许可,您可以将它作为网站服务邮箱的发送引擎,用于推送网站服务信息。

关于Nodemailer的许可:License


安装

npm install nodemailer --save

使用(来自官网)

'use strict';
const nodemailer = require('nodemailer');

// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
    host: 'smtp.example.com',
    port: 465,
    secure: true, // secure:true for port 465, secure:false for port 587
    auth: {
        user: 'username@example.com',
        pass: 'userpass'
    }
});

// setup email data with unicode symbols
let mailOptions = {
    from: '"Fred Foo 👻" <foo@blurdybloop.com>', // sender address
    to: 'bar@blurdybloop.com, baz@blurdybloop.com', // list of receivers
    subject: 'Hello ✔', // Subject line
    text: 'Hello world ?', // plain text body
    html: '<b>Hello world ?</b>' // html body
};

// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.log(error);
    }
    console.log('Message %s sent: %s', info.messageId, info.response);
});

其使用案例可以参考我的一篇文章:
《Node.js使用NodeMailer发送邮件》

地址:Nodemailer


4.视频处理

4.1 ffmpeg

ffmpeg

首先,FFmpeg是一款跨平台的全功能音视频处理解决方案。

它可以对音视频进行录制、转码(h.264、mpeg4、AAC等)、切割,可以将其封装为不同格式(m3u8、mp4、stream等)。

FFmpeg可以安装在Linux、MacOS和Windows中。


fluent-ffmpeg 是基于FFmpeg的一款Node.js中间件。它的所有功能都是以FFmpeg为基础的,因此使用前必须先安装FFmpeg。

fluent-ffmpeg将FFmpeg的命令转换为"fluent",和链式调用一样,让node.js程序更好地调用FFmpeg命令。


篇幅所限,关于 FFmpegfluent-ffmpeg 的安装和使用案例的详细内容,欢迎阅读我的另一篇文章:
《Node.js调用FFmpeg对视频进行切片》


安装

npm install fluent-ffmpeg

简单使用(摘自官方github页面):

var ffmpeg = require('fluent-ffmpeg');

ffmpeg()
  .input('/dev/video0')
  .inputFormat('mov')
  .input('/path/to/file.avi')
  .inputFormat('avi');

地址:fluent-ffmpeg


5.压缩文件(夹)

5.1 archiver

archiver是一款node.js的打包文件、文件夹的工具,它可以打包单个文件、子文件夹下所有文件、字符串、buffer等类型数据到一个zip包里。


安装

npm install archiver --save

简单使用(摘自官网)

// require modules
var fs = require('fs');
var archiver = require('archiver');

// create a file to stream archive data to.
var output = fs.createWriteStream(__dirname + '/example.zip');
var archive = archiver('zip', {
    zlib: { level: 9 } // Sets the compression level.
});

// listen for all archive data to be written
output.on('close', function() {
  console.log(archive.pointer() + ' total bytes');
  console.log('archiver has been finalized and the output file descriptor has closed.');
});

// good practice to catch warnings (ie stat failures and other non-blocking errors)
archive.on('warning', function(err) {
  if (err.code === 'ENOENT') {
      // log warning
  } else {
      // throw error
      throw err;
  }
});

// good practice to catch this error explicitly
archive.on('error', function(err) {
  throw err;
});

// pipe archive data to the file
archive.pipe(output);

// append a file from stream
var file1 = __dirname + '/file1.txt';
archive.append(fs.createReadStream(file1), { name: 'file1.txt' });

// append a file from string
archive.append('string cheese!', { name: 'file2.txt' });

// append a file from buffer
var buffer3 = Buffer.from('buff it!');
archive.append(buffer3, { name: 'file3.txt' });

// append a file
archive.file('file1.txt', { name: 'file4.txt' });

// append files from a sub-directory and naming it `new-subdir` within the archive
archive.directory('subdir/', 'new-subdir');

// append files from a sub-directory, putting its contents at the root of archive
archive.directory('subdir/', false);

// append files from a glob pattern
archive.glob('subdir/*.txt');

// finalize the archive (ie we are done appending files but streams have to finish yet)
archive.finalize();

官网:https://archiverjs.com/docs/#quick-start


6.管理工具

6.1 pm2

启动的应用

pm2是一款管理node.js应用的工具。它可以让你的node应用运行在后台,随时查看每个应用的状态(占用资源、重启次数、持续时长、CPU使用、打印等)。

此外,pm2还支持自动重启:当你的node应用代码有更新后,自动重启服务。这个适用于调试的时候。


安装

npm install pm2 -g

注意这里要加上 -g,表示此工具要安装到全局命令中。Linux系统可能还要手动操作添加链接。


相关使用帮助可阅读:
《用pm2管理node.js应用》


6.2 Supervisor

相比较pm2,Supervisor似乎看起来更适合用于调试代码,便捷的启动方式、监控代码变化自动重启服务都为我们开发量身定做。


安装

npm install supervisor -g

注意这里要加上 -g,表示此工具要安装到全局命令中。Linux系统可能还要手动操作添加链接。


7.加密、签名和校验

7.1 crypto

https://nodejs.org/api/crypto.html

相关资料:RSA签名与验证


相关使用帮助可阅读:
《详细版 | 用Supervisor守护你的Node.js进程》

上一篇 下一篇

猜你喜欢

热点阅读