Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
157
rated 0 times [  161] [ 4]  / answers: 1 / hits: 21187  / 10 Years ago, tue, july 1, 2014, 12:00:00

I'm new in node.js I want to create a simple express.js static file server, but I have some issues.
I have been installed express.js 4.2 globally like this:



npm install  -g express-generator


I have this code in httpsrv.js:



var http = require('http');
var express = require('express');
var app = express();

app.use('/', express.static(__dirname + '/public'));
app.listen(3000, function() { console.log('listening')});


I'm not sure is it ok I guess it is not enough, but I cant run it it's failed with error: cannot find module 'express'.



I want to create a simple http server which can serve from specific folder(public e.g.) and I'm using .html language. I found on the internet a many bullshit, I don't want to use this .jade thing and I don't want to create a empty web app with express etc. I want express.js http server which can operate like Apache and can serve a static html pages first from a specified folder.
Can anybody help me on this, suggest a good article which is explain a step by step, because I'm beginner.


More From » node.js

 Answers
18

If you're just trying to serve static files from a directory called public, you might have luck with an app like this:



var path = require('path');
var express = require('express');

var app = express();

var staticPath = path.join(__dirname, '/public');
app.use(express.static(staticPath));

app.listen(3000, function() {
console.log('listening');
});


You'll need to make sure Express is installed. You'll probably run npm install express --save in the same directory as the above JavaScript file. Once you're all ready, you'll run node the_name_of_the_file_above.js to start your server.


[#70354] Sunday, June 29, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
odaliss

Total Points: 342
Total Questions: 102
Total Answers: 98

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
;