How to host an app on node server? - javascript

I have a simple html file that refers to a CSS stylesheet and a javascript file. I'm supposed to host it on a node server. I Googled the procedure and surmised that I was supposed to include the files like so,
var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');
console.log(index);
var javaScriptFile = require('some/javascript/here');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'html'});
res.end(index);
}).listen(10024);
When I run the code, my HTML is rendered but my file treeStructServer.js is shown as an exact copy of the HTML, which causes an error. Any idea why that's happening? I'm out of my depth.

With your current node script you just return the HTML file on every request, no matter what the URL is. You could instead use the node-static module. Install it by running npm install node-static and then replace your Node code with the following:
var static = require('node-static');
//
// Create a node-static server instance to serve the current folder
//
var file = new static.Server('./');
require('http').createServer(function (request, response) {
request.addListener('end', function () {
//
// Serve files!
//
file.serve(request, response);
}).resume();
}).listen(10024);

Related

How to use code which runs in browser and outside browser together (node.js filesystem)

I want to enter path to the folder in browser and display all file names which located inside, i found that it will possible with node fs, but i also have code which runs at browser, and it need vars, located in file, which will run outside of the browser with node. I need to create server with node and runs all code from it? Or what you can reccomend me to reach this goal? PS: By the way i use webpack
There are differences between javascript in browser end and server end. You can't access the directory directly from the browser. You need some sort of backend technology like PHP, Java, node, python, etc in order to get the file list. You can use node server and below code for the reading directory. Then make a simple HTTP request to your backend server from the frontend.
const path = require('path');
const express = require('express');
const fs = require('fs');
const PORT = 3000;
const app = express();
app.get('/getfiles', async (req, res) => {
const directoryPath = path.join(__dirname, 'Documents');
let data = [];
await fs.readdir(directoryPath, function (err, files) {
//handling error
if (err) {
return console.log('Unable to scan directory: ' + err);
}
//listing all files using forEach
files.forEach(function (file) {
// Do whatever you want to do with the file
data.push(file)
});
});
res.send(data);
});
app.listen(PORT, ()=>{
console.log(`server running on port ${PORT}`);
});

Node.js serving HTML file doesn't find referenced files

I'm trying to make a simple game using Node.js and HTML. I want to be able to run the game locally (so localhost). But when I start my Node server, only the HTML content is rendered - my images don't show up and the JS is not loaded. I reference JavaScript files, CSS files and images in the HTML code. Not sure why the server cannot reference these from within the HTML.
Here is my server code:
const path = require('path')
const http = require('http')
var fs = require('fs')
//Set port number:
const port = 3000
const requestHandler = (request, response) => {
console.log(request.url)
response.writeHead(200, {"Content-Type": "text/html"});
response.end(fs.readFileSync('game.html'));
}
const server = http.createServer(requestHandler)
server.listen(port, (err) => {
if (err) {
return console.log('Error: ', err);
}
console.log(`Game started\nGo to http://localhost:3000 to play\n`);
console.log(`Server is listening on ${port}...`);
})
Can anyone tell me how I can get my images/JS loaded?
TIA
You are not serving the static content correctly (i.e. images, CSS). Consider what happens when one navigates to http://localhost:3000/some_image.png - they will be served game.html!
You need to account for users requesting that content in your requestHandler by for example reading the file they want with fs.readFileSync(request.url). Remember to check that they can only request files you want them to be able to read!
You need static handlers to return static content. Check this
https://www.pabbly.com/tutorials/node-js-http-module-serving-static-files-html-css-images/.
Also, if your application is going to be huge then use some middle-ware like Express. (https://expressjs.com/)
If you use express framework, you can use static rendering:
app.use(express.static('public'));
where 'public' is the folder name

Building a Node.js server that parses the URI

I am learning node and have put together a working server and framework. After talking with some more experienced developers, it seems that Im doing unnecessary work to route the URI. Evidently the http module has all of those features build in already, although I am not sure what they are or how to apply them.
Here is my current server.js
// SERVER
var http = require('http');
var url = require('url');
var fs = require('fs');
var lib = require('scripts'); // some custom libraries I use
var path = require('path');
var NodeSession = require("node-session");
var _SESSION = new NodeSession({secret: 'Q3UBzdH9GEfiRCTKbi5MTPyChpzXLsTD'});
// uri slug -> controller file
var routes = {
// Dependencies
'/style' : 'control_style', // CSS stylesheets
'/fonts' : 'control_fonts', // Fonts
'/scripts' : 'control_scripts', // JS library and controls
'/public' : 'control_public', // Public Resources
// Page Routes
'/' : 'control_home', // root path
'/login' : 'control_login', // login path
'/logout' : 'control_logout', // logout path
'/admin' : 'control_admin', // admin panel path
'/test' : 'control_test', // test page
'/upload' : 'control_upload', // upload test page
};
// Main Loop
function start(){
var port = process.env.PORT || 8080;
http.createServer(function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
_SESSION.startSession(request, response, function(){
lib._post(request, function(_POST, form, files){ // grabs and parses post data
// file system objects that may be needed in controllers
var _SYSTEM = {fs, form, files, path, pathname};
// get the respective controller module
var module = routes[pathname];
// hack for uri's referencing public directory
if(pathname.includes('/public')) module = routes['/public'];
if(module!=null) { // load the respective controller
console.log("controller: "+module+".js");
var controller = require("../controller/"+module);
controller.data(response, request, _SYSTEM, _POST, _SESSION);
} else { // Not Found
console.log(pathname+' => Not Found');
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Path not found");
response.end();
}
});
});
}).listen(port);
console.log("Server has started.");
}
exports.start = start;
Basically, Im matching each URI to a key in the "routes" object and loading the respective controller. (Normally, I would extend this functionality using Regex, but just keeping it simple for now).
Does the Node "http" module (or any other module) already have built-in the functions to parse URI such that I dont have to use a custom built router?
Please note: I am using native node and trying to avoid Express.js for this particular exercise
Note: This answer was written before this additional requirement was added to the answer: "I am using native node and trying to avoid using Express for this particular exercise"
There are a lot of Node modules that can be used to simplify what you do here.
For example you can use Express:
var app = require('express')();
app.get('/path1', path1Handler);
app.get('/path2', path2Handler);
app.use('/static', express.static(pathToStaticFiles));
app.listen(3333);
etc.
See: http://expressjs.com/

making js and other files available to html via node.js http server

I have a very simple web server like this:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
fs.readFile('./index.html', 'utf-8', function (err, content) {
if (err) {
res.end('something went wrong.');
return;
}
res.end(content);
});
}).listen(8080);
console.log("Server running on port 8080.")
This renders my index.html without any issues, but if I try to reference another file in my index.html via a script tag for instance, the site just gets stuck, unable to find the file which exists in the server directory.
How can I make those files available to my index.html file?
Please keep in mind that I realize this can be done much more easily with Express but I do not wish to use Express. I am trying to learn how things work behind the scene. Thanks in advance.
You need to make the directory visible to public. Its is recommend to use framework while developing the Node.js application.
Here is the code below to server file without framework.
var basePath = __dirname;
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function(req, res) {
var stream = fs.createReadStream(path.join(basePath, req.url));
stream.on('error', function() {
res.writeHead(404);
res.end();
});
stream.pipe(res);
}).listen(9999);
Refer : Node itself can serve static files without express or any other module..?

Node.js server gives problems with scripts and images

I just started using node js and I've moved one of my websites on it:
var http = require('http');
var fs = require('fs');
var app = http.createServer(function (req, res) {
fs.readFile('./index.html', 'utf-8', function(error, content) {
res.writeHead(200, {'Content-Type' : 'text/html'});
res.end(content);
});
});
app.listen(8080);
The index.html is my website home page. With only html it works, but if i put tags in it (for including jquery for example), it gives JS errors in firebug : Uncaught syntax error : unexpected token < in jquery.js, and then of course '$ is undefined'.
It doesn't load images either.
I don't really need to do some routing or use Express framework or anything, it's just a simple one-page website.
What am I doing wrong ?
Your server isn't handling requests for images or other resources. All requests are given the same response of the ./index.html page.
This means that if an external script or an image is included in the page, when a request is made by the browser for those resources, the original index.html page will be delivered instead.
NodeJS is fairly low-level. You need to set up your server to manually handle requests for different types of resources based on the URL for each request.
Your best bet will be to read through some NodeJS tutorials. They should cover the basics of serving content, though many of them won't deal with the lower-level details, and will suggest packages like Connect or Express.
Change your code to this, and you'll see all the resources being requested.
var http = require('http');
var fs = require('fs');
var url = require('url');
var path = require('path');
var app = http.createServer(function (req, res) {
var pathname = url.parse(req.url).pathname;
var ext = path.extname(pathname).toLowerCase();
console.log(pathname);
if (ext === ".html") {
fs.readFile('./index.html', 'utf-8', function(error, content) {
res.writeHead(200, {'Content-Type' : 'text/html'});
res.end(content);
});
}
});
app.listen(8080);

Categories