node文件服务器,Node.js快速文件服务器(HTTP上的静态文件)

本文介绍如何使用Node.js创建一个简单的HTTP服务器,该服务器能够处理不同类型的静态资源请求,并设置跨源资源共享(CORS)以允许外部访问。文章还提供了一段ES6版本的代码示例,演示了如何读取和响应各种文件类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

UPDATE 如果您需要从外部需求/文件访问您的服务器,你需要克服CORS,在你的Node.js文件中写入以下,正如我在前面的回答中提到这里// Website you wish to allow to connectresponse.setHeader('Access-Control-Allow-Origin', '*');// Request methods you wish to allowresponse.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');// Request headers you wish to allowresponse.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);

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值