lai yoke hman lai yoke hman - 1 month ago 8
Javascript Question

Learnyounode tutorial#11 HTTP File Server

The following is my code

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]);


if i pass path or path2 to fs.createReadStream(), my code works, but if i pass arguments[3], it fails, console.log(path3) also prints undefined. I don't understand this. Someone please explain. Thanks.

Answer

Congratulation you just discovered the arguments attribute of the function object of the JS please refer MDN Docs to know more about it

The arguments object is an Array-like object corresponding to the arguments passed to a function.

try console.log(arguments) or

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]);

notice I've changed the name of the arguments to parguments

Comments