Skip to content

node常见的业务场景及工具

本文介绍一些业务场景下借助node工具实现功能开发

node实现文件夹的压缩和文件解压缩

这里使用一个常用的Npm包--compressing

压缩整个文件夹

js
var compressing = require("compressing");
//压缩文件夹test 为 test.zip
compressing.zip.compressDir(__dirname+"/test/", "test.zip")
.then(() => {
    console.log('zip','success');
}).catch(err => {
    console.error('zip',err);
});

1
2
3
4
5
6
7
8
9

解压缩文件

js
const compressing = require("compressing");
const path = require('path');

// 解压文件 test.zip
compressing.zip.uncompress(__dirname+"/test.zip", path.resolve('test2'))
.then(() => {
    console.log('unzip','success');
}).catch(err => {
    console.error('unzip',err);
});

1
2
3
4
5
6
7
8
9
10
11

邮件

使用node发送邮件是一个很常用的功能,可以封装一个模块来实现邮件服务功能

js
let nodemailer = require('nodemailer')
let smtpTransport = require('nodemailer-smtp-transport')

smtpTransport = nodemailer.createTransport(
  smtpTransport({
    // host: 'smtp.163.com',
    // port: 465,
    // auth: {
    //   user: 'liutaohangzhou@163.com',
    //   pass: '',
    // },
    host: 'smtp.126.com',
    port: 465,
    auth: {
      user: 'liutaochuzhou@126.com',
      pass: '', //这是邮箱的授权码不是登录密码。 安全登录的客户端专用密码:
    },
  })
)
// 邮件接收者、主题、邮件内容都是可以通过参数传递进来
let sendMail = (recipient, subject, html) => {
  smtpTransport.sendMail(
    {
      from: 'liutaochuzhou@126.com',
      to: 'liutaohangzhou@163.com', // recipient ,接收者
      subject: '测试邮件', // subject
      html: '这是一封测试邮件', // html
    },
    (error, response) => {
      if (error) console.log(error)
      else console.log('发送成功')
    }
  )
}

sendMail()
//module.exports = sendMail  // 可以这样模块封装提供服务
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

文本转语音

可以使用谷歌或者科大讯飞的文本转语音,这里介绍谷歌的一个Npm包@google-cloud/text-to-speech

js
const textToSpeech = require('@google-cloud/text-to-speech');
const fs = require('fs');
const util = require('util');
// Creates a client
const client = new textToSpeech.TextToSpeechClient();
async function quickStart() {
  const text = 'hello, world!';
  const request = {
    input: {text: text},
    voice: {languageCode: 'en-US', ssmlGender: 'NEUTRAL'},
    audioConfig: {audioEncoding: 'MP3'},
  };
  const [response] = await client.synthesizeSpeech(request);
  const writeFile = util.promisify(fs.writeFile);
  await writeFile('output.mp3', response.audioContent, 'binary');
  console.log('Audio content written to file: output.mp3');
}
quickStart();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18