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);
Related
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');
I'm new programmer to node.js. I trying to create vanilla server in node.js. In my client, I used ES6 modules. when I start my server and search for http://localhost:3000/ in my browser, HTML and CSS loaded but for javascript have this error:
I have four javascript modules for client side and in HTML I use this code for load javascript moduls:
<script type="module" src="js/controller.js" async></script>
My server code :
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 3000;
const server = http.createServer();
server.on('request', (req, res) => {
let routes = {
'GET': {
'/': indexHtml,
}
}
console.log(req.url)
let handler = routes[req.method][req.url];
handler = handler || readFile;
handler(req, res);
})
server.listen(PORT, () => {
console.log(`Listening on port ${PORT}...`)
});
function indexHtml(req, res) {
readFile({ url: '/index.html' }, res);
}
function readFile(req, res) {
var filePath = path.join(__dirname, '../client/', req.url);
// console.log(filePath)
fs.readFile(filePath, (error, data) => {
if (error) {
res.writeHead(404);
res.write('Not found error 404');
res.end()
} else {
res.writeHead(200);
res.write(data);
res.end();
}
})
}
How can I solve this error and serve javascript modules, Thanks a lot for your help.
With comment #derpirscher, I change my reader function with this code :
function readFile(req, res) {
var filePath = path.join(__dirname, '../client/', req.url);
fs.readFile(filePath, (error, data) => {
if (error) {
res.setHeader('Content-Type', 'text/html');
res.writeHead(404);
res.write('Not found error 404');
res.end()
} else {
const url = req.url === '/' ? '/index.html' : req.url;
if (req.url.includes('js')) res.setHeader('Content-Type', 'application/javascript');
if (req.url.includes('css')) res.setHeader('Content-Type', 'text/css');
if (req.url.includes('html')) res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.write(data);
res.end();
}
})
}
I cant understand how and where to use response.end(). i get it working when loading only single response but when i try to load (say) two html files (index and form in my case) , the server does not load anything.
if i put res.end() after loading the index html it works but server closes.
var http = require('http');
var formidable = require('formidable');
var url=require('url');
var path=require('path');
var fs=require('fs');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
filepath=path.join(__dirname,'index.html');
fs.readFile(filepath,null,function(err,data){
if(err){
res.writeHead(404);
res.write(err+" Error");
}
else{
res.write(data);
}
res.end();
});
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function () {
res.write('File uploaded');
res.end();
});
} else {
var q=url.parse(req.url,true);
var filename=path.join(__dirname,q.pathname);
console.log(filename);
fs.readFile(filename,function(err,data){
if (err) {
res.writeHead(404);
res.write(err+"404 Not Found");
}
else{
res.write(data);
}
res.end();
})
}
}).listen(8080);
Other tips on improving code is much appreciated :)
var http = require('http');
var formidable = require('formidable');
var url = require('url');
var path = require('path');
var fs = require('fs');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function () {
res.write('File uploaded');
res.end();
});
} else if (req.url.length > 1) {
var q = url.parse(req.url, true);
var filename = path.join(__dirname, q.pathname);
console.log(filename);
fs.readFile(filename, function (err, data) {
if (err) {
res.writeHead(404);
res.write(err + "404 Not Found");
}
else {
res.write(data);
}
res.end();
})
} else {
filepath = path.join(__dirname, 'index.html');
fs.readFile(filepath, null, function (err, data) {
if (err) {
res.writeHead(404);
res.write(err + " Error");
}
else {
res.write(data);
}
res.end();
});
}
}).listen(8080);
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) {
});
var http = require('http');
http.createServer(function (req, res) {
if (req.url == '/')
{
req.url += "a.html";
//facebookAPI(req,res);
}
}).listen(1337);
when I typed the address in the browser it was not calling that url.
Any thought Thank you.
Here is how you could serve that file. This is untested!
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
if (req.url == '/')
{
fs.readFile('a.html', 'utf8', function(err, data) {
if(err) {
res.end('Error Loading File');
return;
}
res.end(data);
});
} else {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('file not found');
}
}).listen(1337);
There are better ways to accomplish the same thing, but this should get you started.