8

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.

4

3 回答 3

21

如果您只是想从名为“public”的目录中提供静态文件,那么您可能会遇到这样的应用程序:

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');
});

您需要确保已安装 Express。您可能会npm install express --save在与上述 JavaScript 文件相同的目录中运行。准备就绪后,您将运行node the_name_of_the_file_above.js以启动服务器。

于 2014-07-02T01:13:05.633 回答
11

首先安装 express 模块,尽管 express-generator

npm install express

试试这个删除公共

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

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

它工作正常。

于 2014-12-10T07:38:35.133 回答
1

这个问题甚至不需要任何代码或框架;从npm安装 http-server ,导航到命令提示符中的文件夹并运行以下命令:

http-server

它将启动一个轻量级 http 服务器并立即从文件夹中提供静态内容,可以使用http://localhost查看

于 2015-12-15T14:23:06.263 回答