Server closes after loading homepage (locally) - node.js

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

Related

How to require a JSON file with a node HTTP server response (without express)

I just set up my first node HTTP server, and I am trying to get the response data from a JSON file in my application. When I declare a JSON object in the server.js file, all works well.
data = "{"sample json" : "this is a test"}";
But I want to replace data with a static JSON file at data/sample.json
Here's an example in my server.js file
const http = require("http");
const hostname = "localhost";
const port = 3000;
const server = http.createServer(function(req, res) {
data = // this is where I want to get the JSON data from data/sample.json
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(data);
res.end();
});
Solved with fs.readFile()
const http = require("http");
const hostname = "localhost";
const port = 3000;
const fs = require('fs');
const server = http.createServer(function(req, res) {
filePath = './data/sample.json';
if (req.path == '/data/sample.json') {
fs.readFile(filePath, function(error, content) {
if (error) {
if (error.code == 'ENOENT') {
response.writeHead(404);
response.end(error.code);
}
else {
response.writeHead(500);
response.end(error.code);
}
}
else {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(content);
}
});
}
else {
response.writeHead(404);
response.end('restricted path');
}
});
In case someone else tumbles upon this question. The answer above has ton of typos and errors and incomplete. Here is a working solution.
const http = require("http");
const hostname = "localhost";
const fs = require('fs');
const port = 8080;
const server = http.createServer(function(req, res) {
filePath = './data/sample.json';
if (req.url == '/api/data') {
fs.readFile(filePath, function(error, content) {
if (error) {
if (error.code == 'ENOENT') {
res.writeHead(404);
res.end(error.code);
}
else {
res.writeHead(500);
res.end(error.code);
}
}
else {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(content);
}
});
}
else {
res.writeHead(404);
res.end('404 NOT FOUND');
}
});
server.listen(port, hostname, () => {
console.log('Server started on port ', port);
});

How serve client javascript modules in node.js

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

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

How to upload a file in NodeJS without Express

I'm trying to pick up a file from a form and save it to myself on disk in any folder. I would like to do it by sockets, but I do not know how to handle it. Can someone help me?
This is my code:
main.js
var http = require('http');
var fs = require('fs');
var io = require('socket.io');
var path = require('path');
var server = http.createServer(function (req, res) {
fs.readFile(__dirname + '/index.html', function (err, data) {
if (err) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("Not Found");
res.end();
} else {
res.write(data, 'utf8');
res.end();
}
});
}).listen(8000);
var listener = io.listen(server);
listener.sockets.on('connection', function (socket) {
console.log("Connected");
socket.on('disconnect', function () {
console.log("Disconnect");
});
socket.on('form.message', function (data) {
// here to handle the file ??
socket.emit('new.message', {msg: data});
});
});
index.html(client)
<script>
$(function () {
var socket = io.connect();
var $messageForm = $('#messageForm');
var $file = $('#file');
var $outputFile = $('#outputFile');
var obj = {
file: $file.val(),
};
e.preventDefault();
console.log(obj);
socket.emit('form.message', obj);
$file.val('');
socket.on('new.message', function (data) {
$outputFile.append('<div class="well">' + data.msg.file + '</div>');
});
});
</script>

why it is not calling a.html

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.

Resources