打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
NodeJS -- 自定义模块
定义模块类:
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

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
专门针对初学者的Node.js教程
开源的api文档管理系统
Velocity.js
Node.js如何响应Ajax的POST请求并且保存为JSON文件详解
《Node js项目实战》05TF物业服务端用户管理功能
node.js从入门到菜鸟——资源无法载入?你需要学会地址解析
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服