Node.js Tips Summary

  • 如何按行读取文本文件
function read_file(path, onreadline) {
    let fs = require('fs')
    let readline = require('readline')
    let index = 0
 
    var r = readline.createInterface({
        input : fs.createReadStream(path),
        output : process.stdout,
        terminal : false
    })
 
    r.on('line', function(line) {
        onreadline(line, index++)
    })
}
 
function onreadline(data) {
    console.log(data)
}
 
read_file('book.txt', onreadline)
  • 使用 Promise 对象异步编程
async function get_value(key) {
    return new Promise((resolve, reject) => {
        var fn = () => {
            if (key > 3) {
                reject('Too big')
            }
            else {
                resolve(key * key)
            }
        }
        setTimeout(fn, 1000)
    })
}
 
async function test(key) {
    console.log(`test ${key} begin`)
    var ret = await get_value(key);
    console.log(`ret(${key}) = ${ret}`)
}
 
test(1)
test(2)
test(3)
test(4)
test 1 begin
test 2 begin
test 3 begin
test 4 begin
<1 second after...>
ret(1) = 1
ret(2) = 4
ret(3) = 9
Uncaught (in promise) Too big