2014-09-01 68 views
7

爲什麼運行下面顯示的代碼時出現錯誤? (它在作業的一個應用在斯坦福大學啓動工程「課程Coursera:https://class.coursera.org/startup-001/quiz/attempt?quiz_id=149爲什麼我得到「TypeError:object is not a function」運行這個例子node.js代碼?

課程在六月至2013年9月跑了,所以有可能是已經打破了腳本更新節點或CSV,也許?作業不是修復腳本,所以這個問題不是'欺騙',並且當然目前還沒有運行。

所以,環境是: Ubuntu 14.04(kernel 3-13-0- 29通用), 節點v0.11.13, NPM v1.4.9

而且我npm install「d CSV,佔UTIL並在主目錄restler,腳本也在那兒。

這我徹底難倒.... :-(

錯誤消息:

[[email protected]:~]$node market-research.js 
Invoked at command line. 
Wrote market-research.csv 
Symbol Name Market Cap  Previous Close Price P/E Ratio  Shares EPS Earnings 
/home/ubuntu/market-research.js:47 
    csv() 
    ^
TypeError: object is not a function 
    at csv2console (/home/ubuntu/market-research.js:47:5) 
    at Request.response2console (/home/ubuntu/market-research.js:65:13) 
    at Request.EventEmitter.emit (events.js:110:17) 
    at Request.mixin._fireSuccess (/home/ubuntu/node_modules/restler/lib/restler.js:226:10) 
    at /home/ubuntu/node_modules/restler/lib/restler.js:158:20 
    at IncomingMessage.parsers.auto (/home/ubuntu/node_modules/restler/lib/restler.js:394:7) 
    at Request.mixin._encode (/home/ubuntu/node_modules/restler/lib/restler.js:195:29) 
    at /home/ubuntu/node_modules/restler/lib/restler.js:154:16 
    at Request.mixin._decode (/home/ubuntu/node_modules/restler/lib/restler.js:170:7) 
    at IncomingMessage.<anonymous> (/home/ubuntu/node_modules/restler/lib/restler.js:147:14) 
[[email protected]:~]$ 

代碼:

由腳本創建市場research.csv的
#!/usr/bin/env node 
    /* 
    Use the Yahoo Finance CSV API to do some basic market research calculations. 

    - Background: http://greenido.wordpress.com/2009/12/22/yahoo-finance-hidden-api/ 
    - Example URL: http://finance.yahoo.com/d/quotes.csv?s=GOOG+FB+AAPL&f=snj1pr 
     s: Symbol 
     n: Name 
     j1: Market Capitalization (in billions) 
     p: Price-per-share (at previous close) 
     r: Price to Earnings Ratio 

    Further references. 

    - https://github.com/danwrong/restler 
    - https://github.com/wdavidw/node-csv 
    - http://josscrowcroft.github.io/accounting.js 
    - http://stackoverflow.com/questions/4981891/node-js-equivalent-of-pythons-if-name-main 
    - http://nodejs.org/docs/latest/api/util.html#util_util_format_format 

    */ 

    var util = require('util'); 
    var fs = require('fs'); 
    var rest = require('restler'); 
    var csv = require('csv'); 
    var accounting = require('accounting'); 
    var CSVFILE_DEFAULT = "market-research.csv"; 
    var SYMBOLS_DEFAULT = ["GOOG", "FB", "AAPL", "YHOO", "MSFT", "LNKD", "CRM"]; 
    var COLUMNS_DEFAULT = 'snj1pr'; // http://greenido.wordpress.com/2009/12/22/yahoo-finance-hidden-api 
    var HEADERS_DEFAULT = ["Symbol", "Name", "Market Cap", "Previous Close Price", 
          "P/E Ratio", "Shares", "EPS", "Earnings"]; 

    var financeurl = function(symbols, columns) { 
     return util.format(
      'http://finance.yahoo.com/d/quotes.csv?s=%s&f=%s', 
      symbols.join('+'), 
      columns); 
    }; 

    var marketCapFloat = function(marketCapString) { 
     return parseFloat(marketCapString.split('B')[0]) * 1e9; 
    }; 

    var csv2console = function(csvfile, headers) { 
     console.log(headers.join("\t")); 
     csv() 
     .from.path(csvfile) 
     .on('record', function(row, index) { 
      var shares = Math.round(marketCapFloat(row[2])/row[3], 0); 
      var eps = (row[3]/row[4]).toFixed(3); 
      var earnings = accounting.formatMoney(eps * shares); 
      outrow = row.concat([shares, eps, earnings]); 
      console.log(outrow.join("\t")); 
     }); 
    }; 

    var buildfn = function(csvfile, headers) { 
     var response2console = function(result, response) { 
      if (result instanceof Error) { 
       console.error('Error: ' + util.format(response.message)); 
      } else { 
       console.error("Wrote %s", csvfile); 
       fs.writeFileSync(csvfile, result); 
       csv2console(csvfile, headers); 
      } 
     }; 
     return response2console; 
    }; 

    var marketResearch = function(symbols, columns, csvfile, headers) { 
     symbols = symbols || SYMBOLS_DEFAULT; 
     columns = columns || COLUMNS_DEFAULT; 
     csvfile = csvfile || CSVFILE_DEFAULT; 
     headers = headers || HEADERS_DEFAULT; 
     var apiurl = financeurl(symbols, columns); 
     var response2console = buildfn(csvfile, headers); 
     rest.get(apiurl).on('complete', response2console); 
    }; 

    if(require.main == module) { 
     console.error('Invoked at command line.'); 
     var symbols = process.argv; 
     if(symbols.length > 2) { 
      symbols = symbols.slice(2, symbols.length); 
     } else { 
      symbols = undefined; 
     }; 
     marketResearch(symbols); 
    } else { 
     console.error('Invoked via library call'); 
    } 

    exports.marketResearch = marketResearch; 

內容:

"GOOG","Google Inc.",386.6B,569.20,29.49 
    "FB","Facebook, Inc.",194.5B,73.855,78.49 
    "AAPL","Apple Inc.",613.8B,102.25,16.49 
    "YHOO","Yahoo! Inc.",38.302B,38.31,33.11 
    "MSFT","Microsoft Corpora",374.3B,44.88,17.06 
    "LNKD","LinkedIn Corporat",27.747B,223.26,N/A 
    "CRM","Salesforce.com In",36.577B,58.29,N/A 
+0

的模塊CSV安裝正確?你使用的是什麼版本,你在哪裏使用?你有沒有在使用它之前嘗試記錄csv var? – matteospampani 2014-09-01 10:52:46

+1

您確定您使用的是正確版本嗎?當前版本的API似乎與您的代碼不同。 – 2014-09-01 11:13:50

+0

我認爲csv不是一個函數。 csv是一個對象及其暴露函數 csv.generate,csv.parse,csv.transform,csv.stringify; 因此只能使用這些功能中的任何一個... – balaphp 2014-09-01 11:31:35

回答

7

Qua ntas 94重,謝謝你的提示。

12個月前,node-csv的版本爲0.2,但現在爲0.4,API已更改。

我現在寫的CSV控制檯的功能如下:

// part of file market-script.js 
// edited by Jeff Moye (Moyesoft) 
// no attribution in the original file 

var csv2console = function(csvfile, headers) { 
    console.log(headers.join("\t")); 
    var parser = csv.parse(); //create the parser                            

    parser.on('readable', function(){ //the 'record' event no longer exists                     
             // so instead we write a handler for the                    
             // 'readable' event                          
    while(record = parser.read()){  // and read() each record in a loop                             
     var shares = Math.round(marketCapFloat(record[2])/record[3], 0); 
     var eps = (record[3]/record[4]).toFixed(3); 
     var earnings = accounting.formatMoney(eps * shares); 
     outrow = record.concat([shares, eps, earnings]); 
     console.log(outrow.join("\t")); 
    } 
    }); 

    parser.on('error', function(err){ // we may as well have an error handler                     
    console.log(err.message); 
    }); 

    fs.createReadStream(csvfile).pipe(parser); //open file as a stream and pipe it to the parser                
}; 
+1

謝謝!我從來不會想到我自己。 – Mike 2015-03-31 13:28:31

+0

我正在寫結束後的問題我如何解決它? – mithra 2015-08-13 16:23:36

相關問題