Node.js tips

2.23'22

console.log with colors

console.log('\x1b[31m', 'sometext', '\x1b[0m');

First change colors to 31 and then back to terminal color 0

ANSI code

Check if modules exists

require 为同步执行,不存在的模块加载出错后可以直接使用Try catch处理

axios with keepAlive

import axios from 'axios';
import http from 'http';
import https from 'https';

axios({
    httpAgent: new http.Agent({ keepAlive: true }),
    httpsAgent: new https.Agent({ keepAlive: true }),
});

axios with cookie

headers.Cookie

import axios from 'axios';

axios.create({
    headers: {
        Cookie: 'name=value'
    },
    withCredentials: true,
});

使用 axios-cookiejar-support tough-cookie

npm i axios axios-cookiejar-support tough-cookie
import axios from 'axios';
import axiosCookieJarSupport from 'axios-cookiejar-support'
import { CookieJar } from 'tough-cookie';

axiosCookieJarSupport(axios);
const jar = new CookieJar();

axios({
    url,
    withCredentials: true,
    jar,
}).then(response => {
    console.log('jar', jar);
})

服务端与客户端的 Cookie 传递

服务端响应头:Set-Cookie, 从服务端发送 Cookie 到客户端

    Set-Copokie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure; HttpOnly

客户端请求头:Cookie,从客户端发送 Cookie 到服务端。值一般是服务端之前通过 Set-Cookie 发送过来的。

    Cookie: name=value; name2=value2; name3=value3

Read file stream line-by-line

使用 fs.ReadStreamfor await...of (node v11.4.0 以上) 异步循环:

const fs = require('fs');
const readline = require('readline');

async function processLineByLine() {
    const fileStream = fs.createReadStream('input.txt');

    const rl = readline.createInterface({
        input: fileStream,
        crlfDelay: Infinity
    });
    // Note: we use the crlfDelay option to recognize all instances of CR LF
    // ('\r\n') in input.txt as a single line break.

    for await (const line of rl) {
        // Each line in input.txt will be successively available here as `line`.
        console.log(`Line from file: ${line}`);
    }
}

processLineByLine();

参考

ORM

  • TypeORM

  • Sequelize

环境变量管理:dotenv

dotenv可以读取项目根目录下的.env文件配置到 node 中的process.envThe Twelve-Factor建议每个环境单独维护一个环境变量文件,。

注意:尽可能不要提交.env到仓库

btoa 字符串按 Base64 编码

浏览器

    btoa('hello');
    atob('aGVsbG8=');

node

    // encode
    Buffer.from('hello').toString('base64'); // 'aGVsbG8='

    // decode
    Buffer.from('aGVsbG8=', 'base64').toString(); // 'hello'

console.dir: 打印对象的所有层次的属性,并显示语法颜色

默认 console.log 只会打印有限几层的属性,嵌套更深的属性会以 Object显示。如果想查看对象的所有属性值,需要使用 console.dir并添加参数。

console.dir(object, { depth: null, colors: true, })

console.trace: 打印 console.log 所在文件等信息

在控制台看出 console.log 的输出信息,但却不知道是哪个文件哪一行打出来的。可以使用 console.trace 查看。

var originLog = console.log;
console.log = function (text, ignore) {
        originLog(text);
        console.trace()
}
📖