Pau*_*est 583 http fileserver node.js
是否有Node.js随时可用的工具(随附npm),这将有助于我将文件夹内容作为文件服务器通过HTTP公开.
例如,如果我有
D:\Folder\file.zip
D:\Folder\file2.html
D:\Folder\folder\file-in-folder.jpg
Run Code Online (Sandbox Code Playgroud)
然后从D:\Folder\ node node-file-server.js
我开始我可以通过访问文件
http://hostname/file.zip
http://hostname/file2.html
http://hostname/folder/file-in-folder.jpg
Run Code Online (Sandbox Code Playgroud)
为什么我的节点静态文件服务器丢弃请求? 参考一些神秘的
标准node.js静态文件服务器
如果没有这样的工具,我应该使用什么框架?
Mat*_*elf 986
一个好的"随时可用的工具"选项可能是http-server:
npm install http-server -g
Run Code Online (Sandbox Code Playgroud)
要使用它:
cd D:\Folder
http-server
Run Code Online (Sandbox Code Playgroud)
或者,像这样:
http-server D:\Folder
Run Code Online (Sandbox Code Playgroud)
看看:https://github.com/nodeapps/http-server
Has*_*sef 173
如果您不想使用现成工具,可以使用下面的代码,如我在https://developer.mozilla.org/en-US/docs/Node_server_without_framework中所示:
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function (request, response) {
console.log('request starting...');
var filePath = '.' + request.url;
if (filePath == './')
filePath = './index.html';
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.json':
contentType = 'application/json';
break;
case '.png':
contentType = 'image/png';
break;
case '.jpg':
contentType = 'image/jpg';
break;
case '.wav':
contentType = 'audio/wav';
break;
}
fs.readFile(filePath, function(error, content) {
if (error) {
if(error.code == 'ENOENT'){
fs.readFile('./404.html', function(error, content) {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
});
}
else {
response.writeHead(500);
response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
response.end();
}
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
}).listen(8125);
console.log('Server running at http://127.0.0.1:8125/');
Run Code Online (Sandbox Code Playgroud)
UPDATE 如果您需要从外部需求/文件访问您的服务器,你需要克服CORS,在你的Node.js文件中写入以下,正如我在前面的回答中提到这里
// Website you wish to allow to connect
response.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
response.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
response.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
response.setHeader('Access-Control-Allow-Credentials', true);
Run Code Online (Sandbox Code Playgroud)
UPDATE
正如阿德里安所说,在评论中,他写了一个ES6代码并在此处给出了完整的解释,我只是在下面重新发布他的代码,以防代码因原因而离开原始网站:
const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');
const port = process.argv[2] || 9000;
http.createServer(function (req, res) {
console.log(`${req.method} ${req.url}`);
// parse URL
const parsedUrl = url.parse(req.url);
// extract URL path
let pathname = `.${parsedUrl.pathname}`;
// based on the URL path, extract the file extention. e.g. .js, .doc, ...
const ext = path.parse(pathname).ext;
// maps file extention to MIME typere
const map = {
'.ico': 'image/x-icon',
'.html': 'text/html',
'.js': 'text/javascript',
'.json': 'application/json',
'.css': 'text/css',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.wav': 'audio/wav',
'.mp3': 'audio/mpeg',
'.svg': 'image/svg+xml',
'.pdf': 'application/pdf',
'.doc': 'application/msword'
};
fs.exists(pathname, function (exist) {
if(!exist) {
// if the file is not found, return 404
res.statusCode = 404;
res.end(`File ${pathname} not found!`);
return;
}
// if is a directory search for index file matching the extention
if (fs.statSync(pathname).isDirectory()) pathname += '/index' + ext;
// read file from file system
fs.readFile(pathname, function(err, data){
if(err){
res.statusCode = 500;
res.end(`Error getting the file: ${err}.`);
} else {
// if the file is found, set Content-type and send data
res.setHeader('Content-type', map[ext] || 'text/plain' );
res.end(data);
}
});
});
}).listen(parseInt(port));
console.log(`Server listening on port ${port}`);
Run Code Online (Sandbox Code Playgroud)
jak*_*b.g 77
对于想要在NodeJS脚本中运行的服务器的人:
您可以使用expressjs /服务静电它取代connect.static(这是不再作为连接3):
myapp.js:
var http = require('http');
var finalhandler = require('finalhandler');
var serveStatic = require('serve-static');
var serve = serveStatic("./");
var server = http.createServer(function(req, res) {
var done = finalhandler(req, res);
serve(req, res, done);
});
server.listen(8000);
Run Code Online (Sandbox Code Playgroud)
然后从命令行:
$ npm install finalhandler serve-static$ node myapp.jsMat*_*ant 53
我知道它不是Node,但我使用了Python的SimpleHTTPServer:
python -m SimpleHTTPServer [port]
Run Code Online (Sandbox Code Playgroud)
它运行良好,并附带Python.
Ole*_*leg 33
连接可能是你正在寻找的.
安装方便:
npm install connect
Run Code Online (Sandbox Code Playgroud)
然后最基本的静态文件服务器可以写成:
var connect = require('connect'),
directory = '/path/to/Folder';
connect()
.use(connect.static(directory))
.listen(80);
console.log('Listening on port 80.');
Run Code Online (Sandbox Code Playgroud)
DHl*_*aty 19
从 npm@5.2.0npm开始,在通常的 npm 旁边开始安装一个新的二进制文件,称为npx. 所以现在,从当前目录创建静态 http 服务器的一个班轮:
npx serve
Run Code Online (Sandbox Code Playgroud)
或者
npx http-server
Run Code Online (Sandbox Code Playgroud)
pas*_*asx 17
使用npm安装express:https://expressjs.com/en/starter/installing.html
使用以下内容在index.html的同一级别创建名为server.js的文件:
var express = require('express');
var server = express();
server.use('/', express.static(__dirname + '/'));
server.listen(8080);
Run Code Online (Sandbox Code Playgroud)
如果您希望将其放在其他位置,请在第三行设置路径:
server.use('/', express.static(__dirname + '/public'));
Run Code Online (Sandbox Code Playgroud)
CD到包含您的文件的文件夹,并使用此命令从控制台运行节点:
node server.js
Run Code Online (Sandbox Code Playgroud)
浏览本地主机:8080
Jac*_*nkr 13
如果这就是你所需要的,试试这个:
const http = require('http');
const fs = require('fs');
const port = 3000;
const app = http.createServer((req,res) => {
res.writeHead(200);
if (req.url === '/') req.url = '/index.html'; // courtesy of @JosephCho
res.end(fs.readFileSync(__dirname + req.url));
});
app.listen(port);
Run Code Online (Sandbox Code Playgroud)
注意:您需要使用"/index.html"作为地址的一部分,即" http:// localhost:3000/index.html "
Qwe*_*rty 12
http-server,hs- 链接npm i -g http-server // install
hs C:\repos // run with one line?? FTW!!
Run Code Online (Sandbox Code Playgroud)
serveZEIT.co - 链接npm i -g serve // install
serve C:\repos // run with one line?? FTW!!
Run Code Online (Sandbox Code Playgroud)
以下是可用选项,如果这有助于您做出决定.
C:\Users\Qwerty>http-server --help
usage: http-server [path] [options]
options:
-p Port to use [8080]
-a Address to use [0.0.0.0]
-d Show directory listings [true]
-i Display autoIndex [true]
-g --gzip Serve gzip files when possible [false]
-e --ext Default file extension if none supplied [none]
-s --silent Suppress log messages from output
--cors[=headers] Enable CORS via the "Access-Control-Allow-Origin" header
Optionally provide CORS headers list separated by commas
-o [path] Open browser window after starting the server
-c Cache time (max-age) in seconds [3600], e.g. -c10 for 10 seconds.
To disable caching, use -c-1.
-U --utc Use UTC time format in log messages.
-P --proxy Fallback proxy if the request cannot be resolved. e.g.: http://someurl.com
-S --ssl Enable https.
-C --cert Path to ssl cert file (default: cert.pem).
-K --key Path to ssl key file (default: key.pem).
-r --robots Respond to /robots.txt [User-agent: *\nDisallow: /]
-h --help Print this list and exit.
C:\Users\Qwerty>serve --help
Usage: serve.js [options] [command]
Commands:
help Display help
Options:
-a, --auth Serve behind basic auth
-c, --cache Time in milliseconds for caching files in the browser
-n, --clipless Don't copy address to clipboard (disabled by default)
-C, --cors Setup * CORS headers to allow requests from any origin (disabled by default)
-h, --help Output usage information
-i, --ignore Files and directories to ignore
-o, --open Open local address in browser (disabled by default)
-p, --port Port to listen on (defaults to 5000)
-S, --silent Don't log anything to the console
-s, --single Serve single page applications (sets `-c` to 1 day)
-t, --treeless Don't display statics tree (disabled by default)
-u, --unzipped Disable GZIP compression
-v, --version Output the version number
mur*_*zel 11
在普通的 node.js 中:
const http = require('http')
const fs = require('fs')
const path = require('path')
process.on('uncaughtException', err => console.error('uncaughtException', err))
process.on('unhandledRejection', err => console.error('unhandledRejection', err))
const publicFolder = process.argv.length > 2 ? process.argv[2] : '.'
const port = process.argv.length > 3 ? process.argv[3] : 8080
const mediaTypes = {
zip: 'application/zip',
jpg: 'image/jpeg',
html: 'text/html',
/* add more media types */
}
const server = http.createServer(function(request, response) {
console.log(request.method + ' ' + request.url)
const filepath = path.join(publicFolder, request.url)
fs.readFile(filepath, function(err, data) {
if (err) {
response.statusCode = 404
return response.end('File not found or you made an invalid request.')
}
let mediaType = 'text/html'
const ext = path.extname(filepath)
if (ext.length > 0 && mediaTypes.hasOwnProperty(ext.slice(1))) {
mediaType = mediaTypes[ext.slice(1)]
}
response.setHeader('Content-Type', mediaType)
response.end(data)
})
})
server.on('clientError', function onClientError(err, socket) {
console.log('clientError', err)
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n')
})
server.listen(port, '127.0.0.1', function() {
console.log('? Development server is online.')
})
Run Code Online (Sandbox Code Playgroud)
这是一个简单的 node.js 服务器,它只为特定目录中的请求文件提供服务。
用法:
node server.js folder port
Run Code Online (Sandbox Code Playgroud)
folder根据server.js位置可以是绝对的或相对的。默认值是.您执行node server.js命令的目录。
port 默认为 8080,但您可以指定操作系统中可用的任何端口。
在你的情况下,我会这样做:
cd D:\Folder
node server.js
Run Code Online (Sandbox Code Playgroud)
您可以D:\Folder通过键入从浏览器浏览下的文件http://127.0.0.1:8080/somefolder/somefile.html
还有另一个非常好的静态Web服务器:浏览器同步.
它可以使用节点包管理器下载:
npm install -g browser-sync
Run Code Online (Sandbox Code Playgroud)
安装后,导航到cmd提示符中的项目文件夹,然后运行以下命令:
browser-sync start --server --port 3001 --files="./*"
Run Code Online (Sandbox Code Playgroud)
它将开始迎合浏览器中当前文件夹中的所有文件.
可以从BrowserSync中找到更多内容
谢谢.
我对本页上的任何答案都不太满意,但是,下面的方法似乎可以解决问题。
添加server.js具有以下内容的文件:
const express = require('express')
const path = require('path')
const port = process.env.PORT || 3000
const app = express()
// serve static assets normally
app.use(express.static(__dirname + '/dist'))
// handle every other route with index.html, which will contain
// a script tag to your application's JavaScript file(s).
app.get('*', function (request, response){
response.sendFile(path.resolve(__dirname, 'dist', 'index.html'))
})
app.listen(port)
console.log("server started on port " + port)
Run Code Online (Sandbox Code Playgroud)
还要确保您需要express。运行yarn add express --save或npm install express --save根据您的设置(我可以推荐yarn它非常快)。
您可以更改dist为正在提供内容的任何文件夹。对于我的简单项目,我没有从任何文件夹提供服务,因此我只是删除了dist文件名。
然后,您可以跑步node server.js。由于必须将项目上传到Heroku服务器,因此需要在package.json文件中添加以下内容:
"scripts": {
"start": "node server.js"
}
Run Code Online (Sandbox Code Playgroud)
如果您使用Express框架,则可以使用此功能.
要设置简单的文件服务应用,请执行以下操作:
mkdir yourapp
cd yourapp
npm install express
node_modules/express/bin/express
Run Code Online (Sandbox Code Playgroud)
这是我的单文件/轻量级node.js静态文件web-server pet项目,没有依赖,我认为这是一个快速而丰富的工具,它的使用就像在Linux/Unix/macOS终端上发出此命令一样简单(安装node.js(或在Debian/Ubuntu上)时安装Android 或termuxnodejs-legacy:
curl pad.js.org | node
Run Code Online (Sandbox Code Playgroud)
(文档上的Windows用户存在不同的命令)
它支持我认为有用的不同的东西,
curl pad.js.org | node - -h[sudo] npm install -g pad.js安装,然后使用其安装的版本来访问其选项:pad -h[sudo] docker run --restart=always -v /files:/files --name pad.js -d -p 9090:9090 quay.io/ebraminio/pad.js
上面描述的功能主要记录在http://pad.js.org工具的主页上,我使用的一些不错的技巧也是工具源本身也提供的地方!
工具源在GitHub上,欢迎您提供反馈,功能请求和⭐s!
您可以使用 NPM服务为此包,如果您不需要 NodeJS 的东西,它是一个快速且易于使用的工具:
1 - 在您的 PC 上安装软件包:
npm install -g serve
Run Code Online (Sandbox Code Playgroud)
2 - 为您的静态文件夹提供serve <path>:
d:> serve d:\StaticSite
Run Code Online (Sandbox Code Playgroud)
它将显示您的静态文件夹正在服务哪个端口,只需导航到主机,如:
http://localhost:3000
Run Code Online (Sandbox Code Playgroud)
以下为我工作:
创建一个app.js包含以下内容的文件:
// app.js
var fs = require('fs'),
http = require('http');
http.createServer(function (req, res) {
fs.readFile(__dirname + req.url, function (err,data) {
if (err) {
res.writeHead(404);
res.end(JSON.stringify(err));
return;
}
res.writeHead(200);
res.end(data);
});
}).listen(8080);
Run Code Online (Sandbox Code Playgroud)
创建一个index.html包含以下内容的文件:
Hi
Run Code Online (Sandbox Code Playgroud)
启动命令行:
cmd
Run Code Online (Sandbox Code Playgroud)
在下面运行cmd:
node app.js
Run Code Online (Sandbox Code Playgroud)
转到以下 URL,在 chrome 中:
http://localhost:8080/index.html
Run Code Online (Sandbox Code Playgroud)
就这样。希望有帮助。
来源:https : //nodejs.org/en/knowledge/HTTP/servers/how-to-serve-static-files/
| 归档时间: |
|
| 查看次数: |
442813 次 |
| 最近记录: |