How do I fix connect.router? - node.js

I'm working my way through Node for Front End devs, and as people on SO have already pointed out, Connect no longer has a module for routing. Some people have advised using Express, but I'm unsure of the exact syntax.
The example I am working through is hosted here:
github.com/garann/node-for-frontend-devs/blob/master/03-03.js
I would in turn like to finish the tutorial on templating:
js: github.com/garann/node-for-frontend-devs/blob/master/04-02.js
html: github.com/garann/node-for-frontend-devs/blob/master/public/parent.html
and was wondering whether people think it might be better to ditch these Connect based tutes and just learn how to use Express? As routing will most likely require Express anyway..
Thanks to SO excellent spam protection, I've had to remove the https:// portion of the github links.
Thanks for any help.

Try use this: https://github.com/baryshev/connect-route
UPDATE
In your project folder execute:
npm install connect-route
Updated code from your example:
var connect = require("connect");
var connectRoute = require("connect-route");
connect(
connect.static(__dirname + "/public"),
connectRoute(function(app) {
app.get("/sayHello/:firstName/:lastName", function(req, res) {
var userName = req.params.firstName + " " + req.params.lastName,
html = "<!doctype html>" +
"<html><head><title>Hello " + userName + "</title></head>" +
"<body><h1>Hello, " + userName + "!</h1></body></html>";
res.end(html);
});
})
).listen(8000);
Point your browser to:
http://[your_host_here]:8000/sayHello/nick/name

Summary
connect.router was removed in version 2.x. I took the code from 1.x and I published it as connect_router.
Install
npm install --save connect_router
Usage
if (!connect.router) {
connect.router = require('connect_router');
}
function route(rest) {
rest.get('/api/hello', function (req, res) {
res.end('hello');
});
}
app = connect()
.use(connect.router(route))
;
server = app.listen(port, function () {
console.log('listening on', server.address());
});
On Github
https://github.com/coolaj86/connect_router taken from Connect 1.x's router with documentation essentially being the tests
The original documentation is... somewhere.

Related

Where do I put database connection information in a Node.js app?

Node.js is my first backend language and I am at the point where I am asking myself "where do I put the database connection information?".
There is a lot of good information regarding this issue. Unfortunately for me all the examples are in PHP. I get the ideas but I am not confident enough to replicate it in Node.js.
In PHP you would put the information in a config file outside the web root, and include it when you need database data.
How would you do this in Node.js? using the Express.js framework.
So far I have this:
var express = require('express'), app = express();
var mysql = require('mysql');
app.get('/', function(req,res) {
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'store'
});
var query = connection.query('SELECT * from customers where email = "deelo42#gmail.com"');
query.on('error', function(err) {
throw err;
});
query.on('fields', function(fields) {
console.log('this is fields');
});
query.on('result', function(row) {
var first = row.first_name;
var last = row.last_name;
res.render('index.jade', {
title: "My first name is " + first,
category: "My last name is " + last
});
});
});
app.listen(80, function() {
console.log('we are logged in');
});
As you can see I have a basic express application with 1 GET route. This route sets off the function to go to the database and pull out information based on an email address.
At the top of the GET route is the database connection information. Where do I put that? How do I call it? How do I keep it out of web root, and include it like PHP ? Can you please show me in a working example. Thanks!
I use the Express Middleware concept for same and that gives me nice flexibility to manage files.
I am writing a detailed answer, which includes how i am use the config params in app.js to connect to DB.
So my app structure looks something this:
How i connect to DB? (I am using MongoDB, mongoose is ORM, npm install mongoose)
var config = require('./config/config');
var mongoose = require("mongoose");
var connect = function(){
var options = {
server: {
socketOptions:{
keepAlive : 1
}
}
};
mongoose.connect(config.db,options);
};
connect();
under the config folder i also have 'env' folder, which stores the environment related configurations in separate files such as development.js, test.js, production.js
Now as the name suggests, development.js stores the configuration params related to my development environment and same applies to the case of test and production. Now if you wish you can have some more configuration setting such as 'staging' etc.
project-name/config/config.js
var path = require("path");
var extend = require("util")._extend;
var development = require("./env/development");
var test = require("./env/test");
var production = require("./env/production");
var defaults = {
root: path.normalize(__dirname + '/..')
};
module.exports = {
development: extend(development,defaults),
test: extend(test,defaults),
production: extend(production,defaults)
}[process.env.NODE_ENV || "development"]
project-name/config/env/test.js
module.exports = {
db: 'mongodb://localhost/mongoExpress_test'
};
Now you can make it even more descriptive by breaking the URL's into, username, password, port, database, hostname.
For For more details have a look at my repo, where you can find this implementation, in fact now in all of my projects i use the same configuration.
If you are more interested then have a look at Mean.js and Mean.io, they have some better ways to manage all such things. If you are beginner i would recommend to keep it simple and get things going, once you are comfortable, you can perform magic on your own. Cheers
I recommend the 12-factor app style http://12factor.net which keeps all of this in env vars. You never should have this kind of information hard-coded or in the app source-code / repo, so you can reuse it in different environments or even share it publicly without breaking security.
However, since there are lots of environment vars, I tend to keep them together in a single env.js like the previous responder wrote - although it is not in the source code repo - and then source it with https://www.npmjs.org/package/dotenv
An alternative is to do it manually and keep it in, e.g. ./env/dev.json and just require() the file.
Any of these works, the important point is to keep all configuration information separate from code.
I agree with the commenter, put it in a config file. There is no ultimate way, but nconf is also one of my favourites.
The important best practise is that you keep the config separate if you have a semi-public project, so your config file will not overwrite other developers.
config-sample.json (has to be renamed and is tracked with for example git)
config.json (not tracked / ignored by git)

Using directory (for images links etc) in Openshift (nodejs application)

I have a webpage that I have hosted using a node application on openshift. Its here
http://nodejs-volition.rhcloud.com/
My question is very simple (although I haven't found anyone else asking it). How do I refer to other files in the directory which contains index.html
For instance I would like to use an image that is in the directory in the index. My current html for the image is
<img src="$OPENSHIFT_REPO_DIR/images/1416870991752.jpg" alt="spark core">
I have also tried using "images/1416870991752.jpg". I have the same problem with linking to other html files in the directory?
What am I doing wrong? Please help?
As corey112358 alludes to below the key is in that to host using nodejs a server must be defined. My application already has a server file, so rather than creating a new server I must modify the existing one. I've done it successfully now, there were two changes to make to the server.js file.
The 1st change is modification of the cache. That should look like this...
self.zcache['index.html'] = fs.readFileSync('./index.html');
self.zcache['page2.html'] = fs.readFileSync('./page2.html');
self.zcache['sparkcoredark.jpg'] = fs.readFileSync('./sparkcoredark.jpg');
The first line was already included but the next two were added by me to include another html page and an image.
The second step is modify the self.createRoutes section of the server.js file as below (asciimo image is included by default).
self.createRoutes = function() {
self.routes = { };
self.routes['/asciimo'] = function(req, res) {
var link = "http://i.imgur.com/kmbjB.png";
res.send("<html><body><img src='" + link + "'></body></html>");
};
self.routes['/'] = function(req, res) {
res.setHeader('Content-Type', 'text/html');
res.send(self.cache_get('index.html') );
};
self.routes['/page2.html'] = function(req, res) {
res.setHeader('Content-Type', 'text/html');
res.send(self.cache_get('page2.html') );
};
self.routes['/sparkcoredark.jpg'] = function(req, res) {
res.setHeader('Content-Type', 'image/jpg');
res.send(self.cache_get('sparkcoredark.jpg') );
};
};
Hope that helps out anyone else struggling with this issue. Thanks to coreyfibonacci

node.js http-proxy proxy based on url

I would like to create a proxy based on URL, such that you can go to: blah.com:8000/tolley-ltm and it proxies that request to my local workstation such as tolley.internal.blah.com based on the URL. So I could also do blah.com:8000/someguy-ltm and it goes to some guy's workstation at someguy-ltm.internal.blah.com. The end user will only ever see blah.com:8000/tolley-ltm
I have this sort of working, but not 100% and I would like your help! Here is the current code:
var fulltld ="internal.blah.com";
var proxyServer = httpProxy.createProxy();
var options = {
'/tolley-ltm': 'tolley-ltm',
'/someguy-ltm': 'someguy-ltm'
}
require('http').createServer(function(req, res) {
var dest = req.url;
req.url = '/';
fail = function(err){
console.log("Something bad happened: " + err);
}
proxyServer.web(req, res, {
target: {
host: options[dest] + '.' + fulltld,
port: 6109
}
},fail);
}).listen(8000);
So what happens currently is I go to blah.com:8000/tolley-ltm in my browser and it successfully goes to tolley.internal.blah.com:6109, however when I navigate since I changed the req.url to / instead of tolley-ltm every subsequent actions then goes to blah.com:8000/ instead of blah.com:8000/tolley-ltm and this causes the proxy to stop working.
Sidenote: If I don't change the req.url to '/' it ends up proxying to tolley.internal.blah.com:6109/tolley-ltm instead of just tolley.internal.blah.com:6109/
Is there a way I can keep the url to the end user looking like blah.com/8000/tolley-ltm and have all actions call back to blah.com/8000-ltm, such as if I clicked a link to go to /products, it would take me to blah.com/8000/tolley-ltm/products instead of blah.com/8000/products

Node.js - socket.io web app

I've created a basic node.js server program and used socket.io to pass some field data from a client (see below). Pretty chuffed as I'm new to this business. I liked this node-express-socket.io approach as its all Javascript and is apparently usable by most browsers (incl' mobile). The problem is I've kind of fumbled my way through and do not not fully understand what I have created! Two questions...
1) Do I need to use the "//ajax.googleapis.com...jquery..."? This is annoying as the browser will need to have an internet connection to work. Is there another way to access the html doc elements without needing an internet connection?
2) What does the "app.use(express.static...." line do? The "app.get..." function seems to require this to work.
If there are any other general comments about my code please let me have it!
Cheers,
Kirbs
Client side code:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect(document.location.protocol+'//'+document.location.host);
function clicked(){
$(function(){
var makeInput=$('.app').find('#make').val();
var modelInput=$('.app').find('#model').val();
socket.emit('make', makeInput);
socket.emit('model', modelInput);
});
};
</script>
Server side code:
var express = require('express');
var http = require('http');
var socketio = require('socket.io');
var app = express();
var server = http.createServer(app);
var io = socketio.listen(server);
app.use(express.static(__dirname));
app.get('/', function (req, res) {
res.render(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.on('make', function (make) {
socket.on('model',function (model){
console.log('recieved message:', make+','+model);
});
});
});
server.listen(8000);
1) As you have setup a static web server (see answer 2), you could simply download the jquery source and serve the .js file from there.
2) "app.use(express.static...." configure a static webserver and setting up the http root directory to the directory that your node.js script lives, as indicated by the __dirname variable. For more detail, see app.use API reference.
As result, I would recommend you change you app.use to:
app.use(express.static(__dirname + '/public'));
and place all your static files, including your jquery file(s), under a public subdirectory.
Also, your server side code has a dependency on sequence of make and model which should be changed. For example, if you switch the emit order to model then make, you should see that your server's console.log will be picking up the make from the previous call.
Instead, try something like:
// On server:
socket.on('info', function (info) {
console.log('recieved message:', info.make+','+info.model);
});
// On client:
socket.emit('info', { make: makeInput, model: modelInput })
1) You can serve the jQuery library also from your server if you like that better. You should put it in the public/vendor or public/js folder in your project.
2) This is a middleware call from Express framework, which uses in turn the Connect middleware stack. Read up on this here.

Using Node.js as a simple web server

I want to run a very simple HTTP server. Every GET request to example.com should get index.html served to it but as a regular HTML page (i.e., same experience as when you read normal web pages).
Using the code below, I can read the content of index.html. How do I serve index.html as a regular web page?
var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(index);
}).listen(9615);
One suggestion below is complicated and requires me to write a get line for each resource (CSS, JavaScript, images) file I want to use.
How can I serve a single HTML page with some images, CSS and JavaScript?
Simplest Node.js server is just:
$ npm install http-server -g
Now you can run a server via the following commands:
$ cd MyApp
$ http-server
If you're using NPM 5.2.0 or newer, you can use http-server without installing it with npx. This isn't recommended for use in production but is a great way to quickly get a server running on localhost.
$ npx http-server
Or, you can try this, which opens your web browser and enables CORS requests:
$ http-server -o --cors
For more options, check out the documentation for http-server on GitHub, or run:
$ http-server --help
Lots of other nice features and brain-dead-simple deployment to NodeJitsu.
Feature Forks
Of course, you can easily top up the features with your own fork. You might find it's already been done in one of the existing 800+ forks of this project:
https://github.com/nodeapps/http-server/network
Light Server: An Auto Refreshing Alternative
A nice alternative to http-server is light-server. It supports file watching and auto-refreshing and many other features.
$ npm install -g light-server
$ light-server
Add to your directory context menu in Windows Explorer
reg.exe add HKCR\Directory\shell\LightServer\command /ve /t REG_EXPAND_SZ /f /d "\"C:\nodejs\light-server.cmd\" \"-o\" \"-s\" \"%V\""
Simple JSON REST server
If you need to create a simple REST server for a prototype project then json-server might be what you're looking for.
Auto Refreshing Editors
Most web page editors and IDE tools now include a web server that will watch your source files and auto refresh your web page when they change.
I use Live Server with Visual Studio Code.
The open source text editor Brackets also includes a NodeJS static web server. Just open any HTML file in Brackets, press "Live Preview" and it starts a static server and opens your browser at the page. The browser will auto refresh whenever you edit and save the HTML file. This especially useful when testing adaptive web sites. Open your HTML page on multiple browsers/window sizes/devices. Save your HTML page and instantly see if your adaptive stuff is working as they all auto refresh.
Web / SPA / PWA / Mobile / Desktop / Browser Ext Web Developers
Some SPA frameworks include a built in version of the Webpack DevServer that can detect source file changes and trigger an incremental rebuild and patch (called hot reloading) of your SPA or PWA web app. Here's a few popular SPA frameworks that can do this.
VueJS Developers
For VueJS developers, a favorite is Quasar Framework that includes the Webpack DevServer out of the box with switches to support server-side rendering (SSR) and proxy rules to cure your CORS issues. It includes a large number of optimized components designed to adapt for both Mobile and Desktop. These allows you to build one app for ALL platforms (SPA, SPA+SSR, PWA, PWA+SSR, Cordova and Capacitor Mobile AppStore apps, Electron Desktop Node+VueJS apps and even Browser extensions).
Another popular one is NuxtJS that also supports static HTML/CSS code generation as well as SSR or no-SSR build modes with plugins for other UI component suites.
React Framework Developers
ReactJS developers can also setup hot reloading.
Cordova/Capacitor + Ionic Framework Developers
Iconic is a mobile only hybrid component framework that now supports VueJS, React and Angular development. A local server with auto refresh features is baked into the ionic tool. Just run ionic serve from your app folder. Even better ... ionic serve --lab to view auto-refreshing side by side views of both iOS and Android.
Note: This answer is from 2011. However, it is still valid.
You can use Connect and ServeStatic with Node.js for this:
Install connect and serve-static with NPM
$ npm install connect serve-static
Create server.js file with this content:
var connect = require('connect');
var serveStatic = require('serve-static');
connect()
.use(serveStatic(__dirname))
.listen(8080, () => console.log('Server running on 8080...'));
Run with Node.js
$ node server.js
You can now go to http://localhost:8080/yourfile.html
Check out this gist. I'm reproducing it here for reference, but the gist has been regularly updated.
Node.JS static file web server. Put it in your path to fire up servers in any directory, takes an optional port argument.
var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs"),
port = process.argv[2] || 8888;
http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname
, filename = path.join(process.cwd(), uri);
fs.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return;
}
if (fs.statSync(filename).isDirectory()) filename += '/index.html';
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
response.writeHead(200);
response.write(file, "binary");
response.end();
});
});
}).listen(parseInt(port, 10));
console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown");
Update
The gist does handle css and js files. I've used it myself. Using read/write in "binary" mode isn't a problem. That just means that the file isn't interpreted as text by the file library and is unrelated to content-type returned in the response.
The problem with your code is you're always returning a content-type of "text/plain". The above code does not return any content-type, but if you're just using it for HTML, CSS, and JS, a browser can infer those just fine. No content-type is better than a wrong one.
Normally the content-type is a configuration of your web server. So I'm sorry if this doesn't solve your problem, but it worked for me as a simple development server and thought it might help some other people. If you do need correct content-types in the response, you either need to explicitly define them as joeytwiddle has or use a library like Connect that has sensible defaults. The nice thing about this is that it's simple and self-contained (no dependencies).
But I do feel your issue. So here is the combined solution.
var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs")
port = process.argv[2] || 8888;
http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname
, filename = path.join(process.cwd(), uri);
var contentTypesByExtension = {
'.html': "text/html",
'.css': "text/css",
'.js': "text/javascript"
};
fs.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return;
}
if (fs.statSync(filename).isDirectory()) filename += '/index.html';
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
var headers = {};
var contentType = contentTypesByExtension[path.extname(filename)];
if (contentType) headers["Content-Type"] = contentType;
response.writeHead(200, headers);
response.write(file, "binary");
response.end();
});
});
}).listen(parseInt(port, 10));
console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown");
You don't need express. You don't need connect. Node.js does http NATIVELY. All you need to do is return a file dependent on the request:
var http = require('http')
var url = require('url')
var fs = require('fs')
http.createServer(function (request, response) {
var requestUrl = url.parse(request.url)
response.writeHead(200)
fs.createReadStream(requestUrl.pathname).pipe(response) // do NOT use fs's sync methods ANYWHERE on production (e.g readFileSync)
}).listen(9615)
A more full example that ensures requests can't access files underneath a base-directory, and does proper error handling:
var http = require('http')
var url = require('url')
var fs = require('fs')
var path = require('path')
var baseDirectory = __dirname // or whatever base directory you want
var port = 9615
http.createServer(function (request, response) {
try {
var requestUrl = url.parse(request.url)
// need to use path.normalize so people can't access directories underneath baseDirectory
var fsPath = baseDirectory+path.normalize(requestUrl.pathname)
var fileStream = fs.createReadStream(fsPath)
fileStream.pipe(response)
fileStream.on('open', function() {
response.writeHead(200)
})
fileStream.on('error',function(e) {
response.writeHead(404) // assume the file doesn't exist
response.end()
})
} catch(e) {
response.writeHead(500)
response.end() // end the response so browsers don't hang
console.log(e.stack)
}
}).listen(port)
console.log("listening on port "+port)
I think the part you're missing right now is that you're sending:
Content-Type: text/plain
If you want a web browser to render the HTML, you should change this to:
Content-Type: text/html
Step1 (inside command prompt [I hope you cd TO YOUR FOLDER]) : npm install express
Step 2: Create a file server.js
var fs = require("fs");
var host = "127.0.0.1";
var port = 1337;
var express = require("express");
var app = express();
app.use(express.static(__dirname + "/public")); //use static files in ROOT/public folder
app.get("/", function(request, response){ //root dir
response.send("Hello!!");
});
app.listen(port, host);
Please note, you should add WATCHFILE (or use nodemon) too. Above code is only for a simple connection server.
STEP 3: node server.js or nodemon server.js
There is now more easy method if you just want host simple HTTP server.
npm install -g http-server
and open our directory and type http-server
https://www.npmjs.org/package/http-server
The fast way:
var express = require('express');
var app = express();
app.use('/', express.static(__dirname + '/../public')); // ← adjust
app.listen(3000, function() { console.log('listening'); });
Your way:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
console.dir(req.url);
// will get you '/' or 'index.html' or 'css/styles.css' ...
// • you need to isolate extension
// • have a small mimetype lookup array/object
// • only there and then reading the file
// • delivering it after setting the right content type
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('ok');
}).listen(3001);
Rather than dealing with a switch statement, I think it's neater to lookup the content type from a dictionary:
var contentTypesByExtension = {
'html': "text/html",
'js': "text/javascript"
};
...
var contentType = contentTypesByExtension[fileExtension] || 'text/plain';
You can just type those in your shell
npx serve
Repo: https://github.com/zeit/serve.
You don't need to use any npm modules to run a simple server, there's a very tiny library called "npm Free Server" for Node:
50 lines of code
Outputs if you are requesting a file or a folder
Gives it a red or green color if it failed or worked
Less than 1KB in size (minified)
Fully commented so you can tweak it as needed
npm-free-server (on GitHub)
This is basically an updated version of the accepted answer for connect version 3:
var connect = require('connect');
var serveStatic = require('serve-static');
var app = connect();
app.use(serveStatic(__dirname, {'index': ['index.html']}));
app.listen(3000);
I also added a default option so that index.html is served as a default.
if you have node installed on you PC probably you have the NPM, if you don't need NodeJS stuff, you can use the serve package for this:
1 - Install the package on your PC:
npm install -g serve
2 - Serve your static folder:
serve <path>
d:> serve d:\StaticSite
It will show you which port your static folder is being served, just navigate to the host like:
http://localhost:3000
I found a interesting library on npm that might be of some use to you. It's called mime(npm install mime or https://github.com/broofa/node-mime) and it can determine the mime type of a file. Here's an example of a webserver I wrote using it:
var mime = require("mime"),http = require("http"),fs = require("fs");
http.createServer(function (req, resp) {
path = unescape(__dirname + req.url)
var code = 200
if(fs.existsSync(path)) {
if(fs.lstatSync(path).isDirectory()) {
if(fs.existsSync(path+"index.html")) {
path += "index.html"
} else {
code = 403
resp.writeHead(code, {"Content-Type": "text/plain"});
resp.end(code+" "+http.STATUS_CODES[code]+" "+req.url);
}
}
resp.writeHead(code, {"Content-Type": mime.lookup(path)})
fs.readFile(path, function (e, r) {
resp.end(r);
})
} else {
code = 404
resp.writeHead(code, {"Content-Type":"text/plain"});
resp.end(code+" "+http.STATUS_CODES[code]+" "+req.url);
}
console.log("GET "+code+" "+http.STATUS_CODES[code]+" "+req.url)
}).listen(9000,"localhost");
console.log("Listening at http://localhost:9000")
This will serve any regular text or image file (.html, .css, .js, .pdf, .jpg, .png, .m4a and .mp3 are the extensions I've tested, but it theory it should work for everything)
Developer Notes
Here is an example of output that I got with it:
Listening at http://localhost:9000
GET 200 OK /cloud
GET 404 Not Found /cloud/favicon.ico
GET 200 OK /cloud/icon.png
GET 200 OK /
GET 200 OK /501.png
GET 200 OK /cloud/manifest.json
GET 200 OK /config.log
GET 200 OK /export1.png
GET 200 OK /Chrome3DGlasses.pdf
GET 200 OK /cloud
GET 200 OK /-1
GET 200 OK /Delta-Vs_for_inner_Solar_System.svg
Notice the unescape function in the path construction. This is to allow for filenames with spaces and encoded characters.
Edit:
Node.js sample app Node Chat has the functionality you want.
In it's README.textfile
3. Step is what you are looking for.
step1
create a server that responds with hello world on port 8002
step2
create an index.html and serve it
step3
introduce util.js
change the logic so that any static file is served
show 404 in case no file is found
step4
add jquery-1.4.2.js
add client.js
change index.html to prompt user for nickname
Here is the server.js
Here is the util.js
var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
// change the to 'text/plain' to 'text/html' it will work as your index page
res.end(index);
}).listen(9615);
I think you where searching for this. In your index.html, simply fill it with normal html code - whatever you want to render on it, like:
<html>
<h1>Hello world</h1>
</html>
The way I do it is to first of all install node static server globally via
npm install node-static -g
then navigate to the directory that contains your html files and start the static server with static.
Go to the browser and type localhost:8080/"yourHtmlFile".
Basically copying the accepted answer, but avoiding creating a js file.
$ node
> var connect = require('connect'); connect().use(static('.')).listen(8000);
Found it very convinient.
Update
As of latest version of Express, serve-static has become a separate middleware. Use this to serve:
require('http').createServer(require('serve-static')('.')).listen(3000)
Install serve-static first.
I use below code to start a simple web server which render default html file if no file mentioned in Url.
var http = require('http'),
fs = require('fs'),
url = require('url'),
rootFolder = '/views/',
defaultFileName = '/views/5 Tips on improving Programming Logic Geek Files.htm';
http.createServer(function(req, res){
var fileName = url.parse(req.url).pathname;
// If no file name in Url, use default file name
fileName = (fileName == "/") ? defaultFileName : rootFolder + fileName;
fs.readFile(__dirname + decodeURIComponent(fileName), 'binary',function(err, content){
if (content != null && content != '' ){
res.writeHead(200,{'Content-Length':content.length});
res.write(content);
}
res.end();
});
}).listen(8800);
It will render all js, css and image file, along with all html content.
Agree on statement "No content-type is better than a wrong one"
from w3schools
it is pretty easy to create a node server to serve any file that is requested, and you dont need to install any packages for it
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function (req, res) {
var q = url.parse(req.url, true);
var filename = "." + q.pathname;
fs.readFile(filename, function(err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
http://localhost:8080/file.html
will serve file.html from disk
var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'html'});
res.end(index);
}).listen(9615);
//Just Change The CONTENT TYPE to 'html'
I'm not sure if this is exactly what you wanted, however, you can try changing:
{'Content-Type': 'text/plain'}
to this:
{'Content-Type': 'text/html'}
This will have the browser client display the file as html instead of plain text.
Express function sendFile does exactly what you need, and since you want web server functionality from node, express comes as natural choice and then serving static files becomes as easy as :
res.sendFile('/path_to_your/index.html')
read more here : https://expressjs.com/en/api.html#res.sendFile
A small example with express web server for node:
var express = require('express');
var app = express();
var path = require('path');
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8080);
run this, and navigate to http://localhost:8080
To expand on this to allow you to serve static files like css and images, here's another example :
var express = require('express');
var app = express();
var path = require('path');
app.use(express.static(__dirname + '/css'));
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8080);
so create a subfolder called css, put your static content in it, and it will be available to your index.html for easy reference like :
<link type="text/css" rel="stylesheet" href="/css/style.css" />
Notice relative path in href!
voila!
A slightly more verbose express 4.x version but that provides directory listing, compression, caching and requests logging in a minimal number of lines
var express = require('express');
var compress = require('compression');
var directory = require('serve-index');
var morgan = require('morgan'); //logging for express
var app = express();
var oneDay = 86400000;
app.use(compress());
app.use(morgan());
app.use(express.static('filesdir', { maxAge: oneDay }));
app.use(directory('filesdir', {'icons': true}))
app.listen(process.env.PORT || 8000);
console.log("Ready To serve files !")
Crazy amount of complicated answers here. If you don't intend to process nodeJS files/database but just want to serve static html/css/js/images as your question suggest then simply install the pushstate-server module or similar;
Here's a "one liner" that will create and launch a mini site. Simply paste that entire block in your terminal in the appropriate directory.
mkdir mysite; \
cd mysite; \
npm install pushstate-server --save; \
mkdir app; \
touch app/index.html; \
echo '<h1>Hello World</h1>' > app/index.html; \
touch server.js; \
echo "var server = require('pushstate-server');server.start({ port: 3000, directory: './app' });" > server.js; \
node server.js
Open browser and go to http://localhost:3000. Done.
The server will use the app dir as the root to serve files from. To add additional assets just place them inside that directory.
There are already some great solutions for a simple nodejs server.
There is a one more solution if you need live-reloading as you made changes to your files.
npm install lite-server -g
navigate your directory and do
lite-server
it will open browser for you with live-reloading.
The simpler version which I've came across is as following. For education purposes, it is best, because it does not use any abstract libraries.
var http = require('http'),
url = require('url'),
path = require('path'),
fs = require('fs');
var mimeTypes = {
"html": "text/html",
"mp3":"audio/mpeg",
"mp4":"video/mp4",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"png": "image/png",
"js": "text/javascript",
"css": "text/css"};
http.createServer(function(req, res) {
var uri = url.parse(req.url).pathname;
var filename = path.join(process.cwd(), uri);
fs.exists(filename, function(exists) {
if(!exists) {
console.log("not exists: " + filename);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('404 Not Found\n');
res.end();
return;
}
var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
res.writeHead(200, {'Content-Type':mimeType});
var fileStream = fs.createReadStream(filename);
fileStream.pipe(res);
}); //end path.exists
}).listen(1337);
Now go to browser and open following:
http://127.0.0.1/image.jpg
Here image.jpg should be in same directory as this file.
Hope this helps someone :)
local-web-server is definitely worth a look! Here's an excerpt from the readme:
local-web-server
A lean, modular web server for rapid full-stack development.
Supports HTTP, HTTPS and HTTP2.
Small and 100% personalisable. Load and use only the behaviour required by your project.
Attach a custom view to personalise how activity is visualised.
Programmatic and command-line interfaces.
Use this tool to:
Build any type of front-end web application (static, dynamic, Single Page App, Progessive Web App, React etc).
Prototype a back-end service (REST API, microservice, websocket, Server Sent Events service etc).
Monitor activity, analyse performance, experiment with caching strategy etc.
Local-web-server is a distribution of lws bundled with a "starter pack" of useful middleware.
Synopsis
This package installs the ws command-line tool (take a look at the usage guide).
Static web site
Running ws without any arguments will host the current directory as a static web site. Navigating to the server will render a directory listing or your index.html, if that file exists.
$ ws
Listening on http://mbp.local:8000, http://127.0.0.1:8000, http://192.168.0.100:8000
Static files tutorial.
This clip demonstrates static hosting plus a couple of log output formats - dev and stats.
Single Page Application
Serving a Single Page Application (an app with client-side routing, e.g. a React or Angular app) is as trivial as specifying the name of your single page:
$ ws --spa index.html
With a static site, requests for typical SPA paths (e.g. /user/1, /login) would return 404 Not Found as a file at that location does not exist. However, by marking index.html as the SPA you create this rule:
If a static file is requested (e.g. /css/style.css) then serve it, if not (e.g. /login) then serve the specified SPA and handle the route client-side.
SPA tutorial.
URL rewriting and proxied requests
Another common use case is to forward certain requests to a remote server.
The following command proxies blog post requests from any path beginning with /posts/ to https://jsonplaceholder.typicode.com/posts/. For example, a request for /posts/1 would be proxied to https://jsonplaceholder.typicode.com/posts/1.
$ ws --rewrite '/posts/(.*) -> https://jsonplaceholder.typicode.com/posts/$1'
Rewrite tutorial.
This clip demonstrates the above plus use of --static.extensions to specify a default file extension and --verbose to monitor activity.
HTTPS and HTTP2
For HTTPS or HTTP2, pass the --https or --http2 flags respectively. See the wiki for further configuration options and a guide on how to get the "green padlock" in your browser.
$ lws --http2
Listening at https://mba4.local:8000, https://127.0.0.1:8000, https://192.168.0.200:8000
Most of the answers above describe very nicely how contents are being served. What I was looking as additional was listing of the directory so that other contents of the directory can be browsed. Here is my solution for further readers:
'use strict';
var finalhandler = require('finalhandler');
var http = require('http');
var serveIndex = require('serve-index');
var serveStatic = require('serve-static');
var appRootDir = require('app-root-dir').get();
var log = require(appRootDir + '/log/bunyan.js');
var PORT = process.env.port || 8097;
// Serve directory indexes for reports folder (with icons)
var index = serveIndex('reports/', {'icons': true});
// Serve up files under the folder
var serve = serveStatic('reports/');
// Create server
var server = http.createServer(function onRequest(req, res){
var done = finalhandler(req, res);
serve(req, res, function onNext(err) {
if (err)
return done(err);
index(req, res, done);
})
});
server.listen(PORT, log.info('Server listening on: ', PORT));
This is one of the fastest solutions i use to quickly see web pages
sudo npm install ripple-emulator -g
From then on just enter the directory of your html files and run
ripple emulate
then change the device to Nexus 7 landscape.
Node.js webserver from scratch
No 3rd-party frameworks; Allows query string; Adds trailing slash; Handles 404
Create a public_html subfolder and place all of your content in it.
Gist: https://gist.github.com/veganaize/fc3b9aa393ca688a284c54caf43a3fc3
var fs = require('fs');
require('http').createServer(function(request, response) {
var path = 'public_html'+ request.url.slice(0,
(request.url.indexOf('?')+1 || request.url.length+1) - 1);
fs.stat(path, function(bad_path, path_stat) {
if (bad_path) respond(404);
else if (path_stat.isDirectory() && path.slice(-1) !== '/') {
response.setHeader('Location', path.slice(11)+'/');
respond(301);
} else fs.readFile(path.slice(-1)==='/' ? path+'index.html' : path,
function(bad_file, file_content) {
if (bad_file) respond(404);
else respond(200, file_content);
});
});
function respond(status, content) {
response.statusCode = status;
response.end(content);
}
}).listen(80, function(){console.log('Server running on port 80...')});

Resources