Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Node.js 逐行读取文件 #15

Open
zwhu opened this issue Dec 11, 2015 · 0 comments
Open

Node.js 逐行读取文件 #15

zwhu opened this issue Dec 11, 2015 · 0 comments

Comments

@zwhu
Copy link
Owner

zwhu commented Dec 11, 2015

用 node 来学习「Algorithms(第四版)」的时候,经常遇到逐行读取文件的需求,索性用 node 自带的readLine Api 写个逐行读取文件的程序。

import {createReadStream} from 'fs'
import {createInterface} from 'readline'

let readFile = (inputFile, cb) => {
  let inStream = createReadStream(inputFile, 'utf8')
    , rl       = createInterface({input: inStream})

  rl.on('line', function (line) {
    rl.pause()
    //sync
    cb(line)
    rl.resume()
  })
}
export default readFile

用法比较简单

import {join} from 'path'
import readFile from './readFile'

readFile(join(__dirname, './path.txt'), (line)=> {
  console.log(line)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant