NodeJS静态资源路径统一处理

本文介绍了如何在NodeJS中统一处理静态资源路径,通过目录结构和代码示例,展示了如何处理读取如read.txt、photo.jpeg等文件的路径,确保静态资源的正确访问。

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

目录结构
  • Apache
    • www
      • read.txt
      • photo.jpeg
      • index.html
代码示例
var http = require('http');
var fs = require('fs');

var server = http.createServer();

var wwwDir = './../../Apache/www/';			// 所有读取文件所在的根目录

server.on('request', (req, res) => {
	
	/*
		req.url 拿到的路径是 端口号后面的
		例如: localhost:3000/index 对应的 path 就是 /index
	*/
    var url = req.url;  				
    var filePath = 'index.html';		// 路径为 '/' 时 文件路径指向index.html
    console.log(`${wwwDir}${filePath}`);
    
    if(url !== '/'){
    	filePath = url;
    }
    
    fs.readFile(`${wwwDir}${filePath}`, (err, data)=>{
    	
    	if(err){
			return res.end('404');
		}
		
		res.end(data); 					//结束响应 并发送响应数据 
    })
})

server.listen('3000', '127.0.0.1', () => {
    console.log('http://localhost:3000/')
})

输入路径
http://localhost:3000/  			# 显示 index.html
http://localhost:3000/index.html	# 显示 index.html
http://localhost:3000/read.txt		# 显示 read.txt
http://localhost:3000/photo.jpeg	# 显示 photo.jpeg
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值