I have the following piece of code as follows:
function(staticPath) {
console.log('static Path = ' +staticPath);
return function(data, response) {
console.log('data = ' +data);
console.log('response = ' +response);
var readStream;
// Fix so routes to /home and /home.html both work.
data = data.replace(/^(\/home)(.html)?$/i, '$1.html');
data = '.' + staticPath + data;
fs.stat(data, function(error, stats) {
if (error || stats.isDirectory()) {
return exports.send404(response);
}
readStream = fs.createReadStream(data);
return readStream.pipe(response);
});
}
}
This function basically parses the path to a HTML file and displays the contents of the file.
I am not able to understand how to call this method from outside.
I am calling it as follows:
staticFile("D:\\Node Applications\\public\\home.html")
I can capture it inside a variable innerFunc and i can call the inner function as innerFunc(response) where response is http's serverResponse of which i have the reference with me but i am not sure how can i pass the data param.
I am not understanding what is happening behind the scenes. Can anyone explain ? Do we encounter such kind of code often in javascript ?
EDIT: To make things clear: There is another method as follows:
function(data, response) {
response.writeHead(200, {
'Content-Type': 'application/json'
});
response.end(JSON.stringify(data));
}
which i call from my node server logic as follows:
http.createServer(function(req, res) {
// A parsed url to work with in case there are parameters
var _url;
// In case the client uses lower case for methods.
req.method = req.method.toUpperCase();
console.log(req.method + ' ' + req.url);
if (req.method !== 'GET') {
res.writeHead(501, {
'Content-Type': 'text/plain'
});
return res.end(req.method + ' is not implemented by this server.');
}
if (_url is something like //localhost:1337/employees) {
//call employee service which returns *data*.
// send the data with a 200 status code
return responder.sendJson(data, res);
});
} else {
// try to send the static file
/*res.writeHead(200);
res.end('static file maybe');*/
console.log('Inside else');
var staticInner = responder.staticFile("D:\\Node Applications\\public\\home.html");
staticInner(res);
}
// res.end('The current time is ' + Date.now())
}).listen(1337, '127.0.0.1');
As one can see there is no data variable to pass to the innerFunc hence, got confused.
data(I think you mean you don't know what isdata, because you would pass it asinnerFunc(data, response)), I'd say you don't know what that function does. It would be good to know that. Also, are you expecting to get as result this:return readStream.pipe(response), or something at all?