2016-01-22 47 views
0

我刚启动了node.js并试图解决下面的问题。 我使用了fs.readfile和异步模块。但它不能正常工作。 任何人都可以告诉我一个示例代码? 预先感谢您节点js:读取两个文件,比较部分文件并输出排序后的文件

例)在同一时间读取两个大文件并按时间排序。 应该拿出一个输出文件中像下面

file A : 

<time=100> james 
<time=210> jordan 
<time=300> cam 
<time=500> joly 
<time=700> car 
..... 
//this is a big file, we need to handle a buffer properly 

file B : 

<time=90> sam 
<time=210> foo 
<time=350> call 
<time=600> seattle 
<time=660> usa 
..... 
//this is a big file, we need to handle a buffer properly 

output file : 

<time=90> sam 
<time=100> james 
<time=210> jordan 
<time=210> foo 
<time=300> cam 
<time=350> call 
<time=500> joly 
<time=600> seattle 
<time=660> usa 
<time=700> car 
... 

回答

1

下面是一个例子:

var fs = require('fs'); 
var Promise = require('bluebird'); 


var readFileAsync = function (filePath) { 
    return new Promise(function (resolve, reject) { 
     fs.readFile(filePath, 'utf8', function (err, data) { 
      if (err) { 
       return reject(err); 
      } 
      resolve(data); 
     }); 

    }); 
}; 

var mergeFileData = function() { 
    return Promise.join(
     readFileAsync('fileA'), 
     readFileAsync('fileB'), 
     function (dataA, dataB) { 
      return mergeAndSortData(dataA, dataB) 
     }); 

}; 

你应该声明mergeAndSortData功能自己。