异步读取js中的文件

时间:2016-03-11 01:33:40

标签: javascript node.js

我有一个文件列表。我有兴趣读出他们的名字和他们包含的行数。我知道有更简单的方法可以做到这一点,但有没有办法使用下面代码的一般结构来实现这一目标?

var fs = require('fs');

var fileList = ['./newtest.js', './globtime.js', './newtest.js'];

var numLines = 0;
var filesCount = 0;

function returnLines () {
    console.log('the length of all files is ' + numLines);
}

function readLines(files) {
    for (file in files) {
        fs.readFile(files[file], function(err, data) {
            if (data != undefined) {
                var array = data.toString().split("\n");
                numLines += array.length;
                filesCount +=1;
                console.log('the length of ' + files[file] + ' is ' + array.length); // get this to work .. 
                if (filesCount == files.length) {
                    returnLines();
                }
            }
       });
    }
}

readLines(fileList);

2 个答案:

答案 0 :(得分:2)

你可以用一个闭包来做到这一点:

var fs = require('fs');

var fileList = ['./newtest.js', './globtime.js', './newtest.js'];

var numLines = 0;
var filesCount = 0;

function returnLines () {
  console.log('the length of all files is ' + numLines);
}

function readLines(files) {

  var readFile = function(name){
    return fs.readFile(name, function(err, data) {
      if (data != undefined) {
        var array = data.toString().split("\n");
        numLines += array.length;
        filesCount +=1;
        console.log('the length of ' + name + ' is ' + array.length); // get this to work .. 
        if (filesCount == files.length) {
            returnLines();
        }
      }
    });
  };

  for (file in files) {
    readFile(files[file]);    
  }
}

readLines(fileList);

答案 1 :(得分:2)

让我用承诺重写你原来的例子:

var Promise = require('bluebird');    
var fileList = ['./newtest.js', './globtime.js', './newtest.js'];

readLines( fileList ).then( function(returnLines) {
  var numLines = 0;

  returnLines.forEach( function(res) {
    console.log( 'the length of ' + res.name + ' is ' + res.numLines );
    numLines += res.numLines;
  });

  console.log( 'the length of all files is ' + numLines );    
});

function readLines( files ) {    
  var promises = [];
  var result = [];
  var readFile = Promise.promisify( require('fs').readFile );

  for(i in files) {
    promises.push( readFile( files[i] )
            .bind({ index: i })
            .then( function(data) {
               result[this.index] = { 
                 name: files[this.index], 
                 numLines: data.toString().split('\n').length 
               };
            })
    )
  }

  return Promise.all( promises ).then( function() {
    return result;
  });    
}