node.js实现静态资源加载的方法——两种方法http及express

一.使用内置http实现静态资源加载

原生node要实现静态资源加载就需要借助其内置模块"fs"中的方法去读取静态资源,然后用response中的方法响应给用户

1.需要用到的模块

javascript 复制代码
const http = require('http');
const fs = require('fs');
const path = require('path');

2.加载静态资源

一个简单的示例代码

javascript 复制代码
fs.readFile('./static/msg.txt', function (err, data) {
            if (err) {
                console.log('留言板读取失败!!!')
            }
            response。end(data)
        })

二.使用express库实现静态资源加载

这里可以直接用static中间件---

1.首先,需要安装express库:

安装密令:npm install express

2.示例代码帮助理解

javascript 复制代码
// static中间件用于托管静态文件。
// 通过使用express.static中间件函数,可以指定从哪个目录提供静态资源,如图片、CSS和JavaScript文件。
const express = require('express')
// 创建服务器
var app = express();
// 使用static中间件
app.use(express.static(__dirname + '/public'))
app.use(function(request,response){
    // 响应信息
    response.writeHead(200, { 'Content-Type': 'text/html' })
    response.end('<img src="/demo01.jpg" width = "100%" />')
});
// 启动服务器
app.listen(52273,function(){
    console.log('服务器监听地址 http://127.0.0.1:52273');
})
相关推荐
掉头发类型的选手4 小时前
Node.js: express 使用 Open SSL
express
贩卖纯净水.8 小时前
Webpack的基本使用 - babel
前端·webpack·node.js
贩卖纯净水.9 小时前
Webpack依赖
前端·webpack·node.js
笑醉踏歌行12 小时前
NVM,Node.Js 管理工具
运维·ubuntu·node.js
chxii14 小时前
1.4 Node.js 的 TCP 和 UDP
node.js
xd000021 天前
11. vue pinia 和react redux、jotai对比
node.js
程序猿小D1 天前
第16节 Node.js 文件系统
linux·服务器·前端·node.js·编辑器·vim
前端老六喔2 天前
🎉 开源项目推荐 | 让你的 TypeScript/React 项目瘦身更简单!
node.js·前端工程化
醉书生ꦿ℘゜এ2 天前
npm error Cannot read properties of null (reading ‘matches‘)
前端·npm·node.js
超级土豆粉2 天前
从0到1写一个适用于Node.js的User Agent生成库
linux·ubuntu·node.js