Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

running my sample app using express.js and node.js

var sys = require("sys"),  
my_http = require("http");  
my_http.createServer(function(request,response){  
    sys.puts("I got kicked");  
    response.writeHeader(200, {"Content-Type": "text/plain"});  
    response.write("Hello World");  
    response.end();  
}).listen(8080);  
sys.puts("Server Running on 8080");

The above is my basic web-server, now i want to run my application which contains a HTML and a JS file. Where would i place those files so that i can access it through my port.

I use Apache and Xampp, so i place my files in htdocs directory and access it via my browser, but in terms of node.js i am totally confused?.

like image 244
Kevin Avatar asked Dec 08 '22 12:12

Kevin


1 Answers

Let's get step by step here.

Identify the location for your application.

Firs identify the location where for your application. Let's take it as C:\your_app. The path doesn’t matter, so feel free to locate the directory wherever is best for you.

Installing Node.js

Here is where we will setup Node.js and Express. Node.js is a framework and Express provides a web server. The web server we need does not need to do anything fancy. The only feature that the web server needs is the ability to provide static files.

To get started download and install Node.JS: http://nodejs.org/

Install Express

Express is a package that execute within Node.js. To install express, in the Command Prompt navigate to your directory for the application which is c:\your_app.

Now lets install Express as a package for Node.js. At the command prompt type “npm install express”. That installed Express and should have created a directory called “node_modules”.

server.js

Now that Express is installed, we need to configure it to execute as a webserver. Create another file in the c:\your_app directory call “server.js”.

var express = require('express');
var app = express();
port = process.argv[2] || 8000;

app.configure(function () {
    app.use(
        "/", //the URL throught which you want to access to you static content
        express.static(__dirname) //where your static content is located in your filesystem
    );
});
app.listen(port); //the port you want to use
console.log("Express server running");

Start Express Web Server in Node.js

In the Command Prompt confirm you are at the c:\your_app directory and execute the following commend.

node server.js 8000

Now the web server should be running on port 8000 and your index.html page should be displayed in the browser.

like image 188
Thalaivar Avatar answered Dec 11 '22 09:12

Thalaivar