---
title: "node js 读取文件内容"
author: "selfcontroller"
date: "2014-06-09T09:11:45Z"
tags: []
categories: ["Web前端"]
slug: "node-js"
draft: false
lastmod: "2014-06-09T09:11:45Z"
id: 2077338
url: "https://selfcontroller.iteye.com/blog/2077338"
---

来段node js  逐行读取文件内容 的代码


```js

function readLines(input, func) {
    var remaining = '';
    input.on('data', function(data) {
        remaining += data;
        var index = remaining.indexOf('\n');
        while (index > -1) {
            var line = remaining.substring(0, index);
            remaining = remaining.substring(index + 1);
            func(line);
            index = remaining.indexOf('\n');
        }

    });

    input.on('end', function() {
        if (remaining.length > 0) {
            func(remaining);
        }
    });
}

function func(data) {
    container.push(data);
}

var input = fs.createReadStream(__dirname + '/ip_arr.txt');
readLines(input, func);

```