Fernando josé Fernando josé - 1 month ago 7
Node.js Question

how use express js and function http create server nodejs

I have de following code in node js:

var app,fs, express;
fs = require('fs');

app = require('http').createServer(function(req, res) {
var file;
file = req.url === '/' ? '/index.html' : req.url;
console.log(req.method + " " + file);
return fs.readFile("./views" + file, function(err, data) {
if (err != null) {
res.write(404);
return res.end("<h1>HTTP 404 - Not Found</h1>");
}
res.writeHead(200);
return res.end(data);
});
});
app.listen(3000, function() {
return console.log("running...);
});


i need insert expressjs in my application for work with express js for example :

app = express();
express = require("express");
app.use(express.bodyParser());
app.use(app.router);

app.get("/form", function (req,res){
res.sendfile("./form.html");
});

http.createServer(app).listen(3000);


how join the two code in one

Answer

By joining 2 code in one , i guess you want to use the middleware you described in 1st file

 var app = express();
 var express = require("express");
 app.use(express.bodyParser());
 app.use(app.router);

 app.get("/form", function (req,res){
  res.sendfile("./form.html");
 });

app.use(function(req, res) {
 var file;
 file = req.url === '/' ? '/index.html' : req.url;
 console.log(req.method + " " + file);
 return fs.readFile("./views" + file, function(err, data) {
 if (err != null) {
    res.write(404);
   return res.end("<h1>HTTP 404 - Not Found</h1>");
 }
res.writeHead(200);
return res.end(data);
})

http.createServer(app).listen(3000);