nodejs function hoisting : why it doesn't work? - node.js

This works:
var http = require('http');
var handler = function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World!');
}
http.createServer(handler).listen(8080);
But this doesn't
var http = require('http');
http.createServer(handler).listen(8080);
var handler = function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World!');
}
I don't understand why since it should with hoisting all the more I got no error.

That's not function hoisting, that's variable hoisting. It's equivalent to this:
var http = require('http');
var handler;
http.createServer(handler).listen(8080);
handler = function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World!');
}
Function hoisting works only for function declarations (the above is a function expression):
var http = require('http');
http.createServer(handler).listen(8080);
function handler(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World!');
}
More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function#Function_declaration_hoisting

var http = require('http');
http.createServer(handler).listen(8080);
var handler = function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World!');
}
In this case the declared function does not yet exist.

Related

How to output the value from Promise to http.createServer?

I need to output the value from the getGasPrice() function on the HTTP page. The function is executed asynchronously.
const web3 = createAlchemyWeb3("https://polygon-mainnet.g.alchemy.com/v2/API-KEY");
const http = require('http');
async function getGasPrice() {
gasPrice = '0';
await web3.eth.getGasPrice(function (error, price) {
gasPrice = price;
});
return gasPrice;
}
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
getGasPrice().then((value) => {
res.write(value);
})
res.end();
}).listen(2000, '127.0.0.1');
When I try to output a value to createServer using res.write(value) nothing happens. And when I output the value console.log(value), the value appears in the console. How do I display the value on the site page?
Try this:
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
getGasPrice().then((value) => {
setStatus(value);
res.write("String(value.code)");
res.end();
})
}).listen(2000, '127.0.0.1');
or
http.createServer(async (req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
let value = await getGasPrice();
setStatus(value);
res.write("String(value.code)");
res.end();
}).listen(2000, '127.0.0.1');

unexpected callback in node.js

var http = require("http");
var fs = require("fs");
http.createServer(function (req, res) {
fs.readFile("demo1.html", function (err, data) {
res.writeHead(200, { "Content-Type": "text/html" });
res.write(data);
return res.end();
});
}).listen(80);
Error :
You don't check for an error in the callback of readFile. If there is an error, data will be undefined and res.write(data) throws the error you see.
var http = require("http");
var fs = require("fs");
http.createServer(function (req, res) {
fs.readFile("demo1.html", function (err, data) {
if (err) {
console.log(err);
res.writeHead(404); //or whatever status code you want to return
} else {
res.writeHead(200, { "Content-Type": "text/html" });
res.write(data);
}
return res.end();
});
}).listen(80);

httpdispatcher returning no or blank response

I have the following simple code for a nodejs server....
var http = require('http');
var port = 1337;
var dispatcher = require('httpdispatcher');
dispatcher.setStaticDirname(__dirname);
dispatcher.setStatic('');
dispatcher.onGet("/page1", function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Page One');
});
var server = http.createServer().listen(port);
server.on('request', function (req, res) {
console.log('GOT');
dispatcher.dispatch(req, res);
});
console.log('Listening on port %s', port);
when I goto http://localhost:1337/index.html it is showing up correctly but when I do http://localhost:1337/page1 nothing happens...how can I get it to function properly...
You need to define your custom dispatcher events, in this case "/page1", before setting the static dispatcher. Otherwise static hogs every possible path remaining to check against the file system.
dispatcher.onGet("/page1", function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Page One');
});
dispatcher.setStaticDirname(__dirname);
dispatcher.setStatic('');
Your revised code will look like this:
var http = require('http');
var port = 1337;
var dispatcher = require('httpdispatcher');
dispatcher.onGet("/page1", function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Page One');
});
dispatcher.setStaticDirname(__dirname);
dispatcher.setStatic('');
var server = http.createServer().listen(port);
server.on('request', function (req, res) {
console.log('GOT');
dispatcher.dispatch(req, res);
});
console.log('Listening on port %s', port);
Tested and works

Node.js web server app problems

I'm working on a Node.js app, using http and httpdispatcher to handle web server requests. I have the following code:
var app = require('http').createServer(handler),
sys = require('util'),
exec = require('child_process').exec,
io = require('socket.io').listen(app),
fs = require('fs'),
dispatcher = require('httpdispatcher');
app.listen(61337);
dispatcher.setStatic('assets');
function puts(error, stdout, stderr) { sys.puts(stdout) }
function handler (request, response) {
dispatcher.dispatch(request, response);
}
dispatcher.onGet("/", function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
fs.readFile('./assets/index.html', 'utf8', function (err,data) {
res.end(data);
});
});
dispatcher.onGet("/api/update", function(req, res) {
exec("sh /path/to/update.sh &", puts);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('1');
});
io.sockets.on('connection', function (socket) {
/** Socket.io coming soon */
});
I get the following errors.
path.js:360
throw new TypeError('Arguments to path.join must be strings');
TypeError: Arguments to path.join must be strings
at path.js:360:15
at Array.filter (native)
at Object.exports.join (path.js:358:36)
at HttpDispatcher.staticListener (***/httpdispatcher.js:81:39)
at ***/httpdispatcher.js:132:3
at HttpChain.next (***/httpdispatcher.js:125:9)
at doDispatch (***/httpdispatcher.js:58:13)
at HttpDispatcher.dispatch (***/httpdispatcher.js:74:14)
at Server.handler (***/app-server.js:19:13)
at Server.<anonymous> (***/socket.io/node_modules/engine.io/lib/server.js:369:22)
The Server.handler (***/app-server.js:19:13) line is dispatcher.dispatch(request, response); in the handler function.. so I'm not sure why it's not sending strings?
I went from using httpdispatcher to express
Here is my working example:
var express = require('express'),
app = express(),
http = require('http').createServer(app).listen(61337),
sys = require('util'),
exec = require('child_process').exec,
io = require('socket.io')(http),
fs = require('fs');
app.use('/assets', express.static('assets'));
function puts(error, stdout, stderr) { sys.puts(stdout) }
app.get("/", function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
fs.readFile('./assets/index.html', 'utf8', function (err,data) {
res.end(data);
});
});
app.get("/api/update", function(req, res) {
exec("sh /path/to/update.sh &", puts);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('1');
});
io.sockets.on('connection', function (socket) {
});

reading a file and output to http

How do I join these to scripts into one as what I have done does not work. I think it is the callbacks that I am getting messed up.
With this code I am able to output text to my browser.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
With this code I am able to read a text file and log it to the console.
fs = require('fs')
fs.readFile('/etc/hosts', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
console.log(data);
});
BUT THIS wont work together, WHY?????????????????
Thanks for the help.
var http = require('http');
http.createServer(function (req, res) {
fs = require('fs')
fs.readFile('/etc/hosts', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
console.log(data);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
});
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
You need to return your response AFTER your readFile finishes. You do this by writing the response in the completion callback of readFile e.g.
http.createServer(function (req, res) {
fs.readFile('/etc/hosts', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
console.log(data);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(data);
});
}).listen(1337, '127.0.0.1');

Resources