How to output the value from Promise to http.createServer? - node.js

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

Related

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

nodejs function hoisting : why it doesn't work?

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.

Why doesn't my 404 error display unless I use res.end()?

I'm learning Node, and I have this code
var http = require('http');
// var data = require('fs').readFileSync(__dirname + '/index.html', 'utf8');
http.createServer(function (req, res) {
if (req.url === '/') {
res.writeHead(200, {"content-type": "text/html"});
var html = require('fs').createReadStream(__dirname + '/index.html');
html.on('data', function (chunk) {
res.write(chunk);
})
}
else if (req.url === '/api') {
var obj = {
firstname: 'John',
lastname: 'Smith'
};
res.writeHead(200, {"content-type": "application/json"});
res.write(JSON.stringify(obj));
}
else {
res.writeHead(404, {"content-type": "text/plain"});
res.write("Error 404: Page not found.");
res.end();
}
}).listen(1337, "127.0.0.1");
console.log('Server listening on port 1337');
For some reason, 404 response will not display unless I use res.end(), even though the other two responses display fine without res.end(). Anyone know why this is?

curl, node: posting JSON data to node server

I'm trying to test a small node server I've written with CURL and for some reason this fails. My script looks like this:
http.createServer(function (req, res)
{
"use strict";
res.writeHead(200, { 'Content-Type': 'text/plain' });
var queryObject = url.parse(req.url, true).query;
if (queryObject) {
if (queryObject.launch === "yes") {
launch();
else {
// what came through?
console.log(req.body);
}
}
}).listen(getPort(), '0.0.0.0');
When I point my browser to:
http://localhost:3000/foo.js?launch=yes
that works fine. My hope is to send some data via JSON so I added a section to see if I could read the body part of the request (the 'else' block). However, when I do this in Curl, I get 'undefined':
curl.exe -i -X POST -H "Content-Type: application/json" -d '{"username":"xyz","password":"xyz"}' http://localhost:3000/foo.js?moo=yes
I'm not sure why this fails.
The problem is that you are treating both requests as if they where GET requests.
In this example I use a different logic for each method. Consider that the req object acts as a ReadStream.
var http = require('http'),
url = require('url');
http.createServer(function (req, res) {
"use strict";
if (req.method == 'POST') {
console.log("POST");
var body = '';
req.on('data', function (data) {
body += data;
console.log("Partial body: " + body);
});
req.on('end', function () {
console.log("Body: " + body);
});
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('post received');
} else {
var queryObject = url.parse(req.url, true).query;
console.log("GET");
res.writeHead(200, {'Content-Type': 'text/plain'});
if (queryObject.launch === "yes") {
res.end("LAUNCHED");
} else {
res.end("NOT LAUNCHED");
}
}
res.writeHead(200, { 'Content-Type': 'text/plain' });
}).listen(3000, '0.0.0.0');

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