分享

NodeJS -- 自定义模块

 arthur_cai 2014-06-04
定义模块类:
parser.js

// Parser constructor.  
var Parser = function() {
};  

// Parses the specified text.
  
Parser.prototype.parse = function(text) {
  var results = {};    
  // Break up the file into lines.  
  var lines = text.split('\n');    
  lines.forEach(function(line) {  
    var parts = line.split(' ');  
    var letter = parts[1];  
    var count = parseInt(parts[2]);    

    if(!results[letter]) {  
      results[letter] = 0;  
    }    
    results[letter] += parseInt(count);  
  });    
  return results;  
};  

// Export the Parser constructor from this module.  
//告诉Node从该文件中要输出的内容
module.exports = Parser;

 

my_parser.js

  1. // Require my new parser.js file.  
  2. var Parser = require('./parser');  
  3.   
  4. // Load the fs (filesystem) module.  
  5. var fs = require('fs');  
  6.   
  7. // Read the contents of the file into memory.  
  8. fs.readFile('example_log.txt'function (err, logData) {  
  9.   
  10.   // If an error occurred, throwing it will  
  11.   // display the exception and kill our app.  
  12.   if (err) throw err;  
  13.   
  14.   // logData is a Buffer, convert to string.  
  15.   var text = logData.toString();  
  16.   
  17.   // Create an instance of the Parser object.  
  18.   var parser = new Parser();  
  19.   
  20.   // Call the parse function.  
  21.   console.log(parser.parse(text));  
  22.   // { A: 2, B: 14, C: 6 }  
  23. });

 

测试结果:
>node my_parser.js

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多