2015-10-20 39 views
2

以下是我的代碼Learnyounode教程#11 HTTP文件服務器

var http = require('http'); 
var fs = require('fs'); 
var arguments = process.argv; 
var path = process.argv[3]; 
var path2 = arguments[3]; 

var server = http.createServer(
    function (req, res) 
    { 

    console.log('path1'+path); 
    console.log('path2'+path2); 
    console.log('path3'+arguments[3]); 
     var fileStream = fs.createReadStream(arguments[3]); 
     fileStream.pipe(res); 
    } 
); 

server.listen(arguments[2]); 

,如果我傳遞給fs.createReadStream()路徑或路徑2,我的代碼工作,但如果我傳遞參數[3],它失敗,console.log(path3)也打印未定義。我不明白這一點。有人請解釋。謝謝。

+0

'path2'打印正確的輸出的名字嗎? – Minato

回答

3

恭喜你剛剛發現了JS的function object的論點attribute請參考MDN Docs更多地瞭解它

參數對象是對應於傳遞給函數的參數數組類對象。

嘗試console.log(arguments)

var http = require('http'); 
var fs = require('fs'); 
var parguments = process.argv; 
var path = process.argv[3]; 
var path2 = parguments[3]; 

var server = http.createServer(
    function (req, res) 
    { 

    console.log('path1'+path); 
    console.log('path2'+path2); 
    console.log('path3'+parguments[3]); 
     var fileStream = fs.createReadStream(parguments[3]); 
     fileStream.pipe(res); 
    } 
); 

server.listen(parguments[2]); 

通知我已經改變了argumentsparguments

+0

嗨,這是你,再次感謝你的幫助!顯然,我還有很多東西要學習JS基礎。 –

0
var http = require('http'); 
var fs = require('fs'); 

var server = http.createServer(function (req, res) { 

res.writeHead(200, { 'content-type': 'text/plain' }) 

fs.createReadStream(process.argv[3]).pipe(res); 
}); 

server.listen(Number(process.argv[2]));