nodejs基本使用

node.js基本使用

 1.压缩并整合html、js文件(注:压缩后放html类型文件里,才可以运行显示页面)

复制代码
//压缩html和js文件
const fs = require('fs')
const path = require('path')
//读取、压缩html文件
fs.readFile(path.join(__dirname, 'index.html'), 'utf8', (err, data) => {
  const compressedHtml = data.replace(/[\r\n]/g, '') //去除回车、换行符且全局替换
  //读取、压缩js文件
  fs.readFile(path.join(__dirname, 'index.js'), 'utf8', (err, data) => {
    const compressedJs = data
      .replace(/[\r\n]/g, '')
      .replace(/console.log\(.+?\);?/g, '') //去除console.log语句 //去除回车、换行符且全局替换
      // .replace(/\/\*[\s\S]*?\*\/|\/\/.*$/g, '') //去除注释
      // .replace(/\s+/g, ' ') //压缩空格
    const result = `<script>${compressedJs}</script>`
    console.log(result)

    //写入压缩后的文件
    fs.writeFile(
      path.join(__dirname, 'dist/index.min.html'),
      compressedHtml + result,
      'utf8',
      (err) => {
        if (err) throw err
        console.log('压缩成功')
      }
    )
  })
})
复制代码

2.开启一个Web服务,设置支持中文字符

复制代码
//1.引入http模块,创建一个http服务器实例
const http = require('http');
const server = http.createServer()

//2.监听request事件,处理请求并返回响应
server.on('request', (req, res) => {   
    // res.end('Hello World') 

    res.setHeader('Content-Type', 'text/html;charset=utf-8') //设置响应头:返回的是普通文本,尝试解析为html标签,编码为utf-8
    res.end('你好世界') //一次请求只能对应一次响应
 })

 //3.启动服务器并监听端口
 server.listen(3000, () => {
    console.log('Server is running on port 3000')
 })
复制代码

 

posted @   Anne起飞记  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示