前端基础知识(Node.js)

前端基础知识(Node.js)

文章目录


一、认识Node.js

Node.js​ 是一个基于 Chrome V8 引擎的 JavaScript 运行时环境,让 JavaScript 可以运行在服务器端。

核心特点:JavaScript 运行时 + 非阻塞I/O + 事件驱动 = Node.js

应用层 (Your Code)

Node.js API (fs, http, path, etc.)

C++ 绑定层 (libuv, zlib, crypto, etc.)

V8 引擎 + libuv (事件循环)

⚡ Node.js 的核心优势

1. 非阻塞 I/O(异步编程)

js 复制代码
// ❌ 阻塞式(传统服务器)
const data = readFileSync('file.txt')  // 线程等待
processData(data)

// ✅ 非阻塞(Node.js)
readFile('file.txt', (err, data) => {  // 立即返回
    processData(data)                   // 回调执行
})
// 这里可以继续执行其他代码

2. 事件驱动架构

js 复制代码
// 事件监听模式
const EventEmitter = require('events')

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter()

// 监听事件
myEmitter.on('event', () => {
    console.log('事件触发!')
})

// 触发事件
myEmitter.emit('event')

3. 单线程但高性能

js 复制代码
传统多线程模型:
┌─────┬─────┬─────┐
│线程1│线程2│线程3│ → 每个请求一个线程
└─────┴─────┴─────┘
    内存消耗大,上下文切换开销

Node.js 单线程模型:
    主线程 ────┐
              ↓
    事件循环 ← 回调队列
              ↑
    线程池 ────┘ (libuv 处理耗时操作)

二、Node.js项目构建

1.首先在 Node.js 官网 下载并安装Node.js 。(npm 会自动随 Node.js 安装)

2.搭建基础项目

shell 复制代码
# 查看环境变量的配置,确定配置好
echo %PATH%
#创建项目目录
mkdir my-project
cd my-project
#推荐使用淘宝镜像,这是现阶段国内最流行的镜像,更新及时,速度快
npm config set registry https://registry.npmmirror.com/
#初始化项目
npm init -y(这里同时创建一个 `package.json` 文件)
npm install bootstrap-icons (安装 Bootstrap Icons,其列为 
`dependencies`,并且在 `node_modules` 文件夹中)
# 验证安装
npm list bootstrap-icons
# 通过npm 脚本启动项目(安装 http-server,这个是本地轻量级的服务器)
npm install --save-dev http-server
# 在 `package.json` 中添加启动脚本
"scripts": {
  "start": "http-server ."
}
# 下载 express 模块
npm install express
# 启动项目
npm start

本地index.html示例:

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Bootstrap Icons Example</title>
  <link href="./node_modules/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
</head>
<body>
  <h1>使用 Bootstrap Icons</h1>
  <i class="bi bi-house-door"></i> <!-- 示例图标 -->
</body>
</html>

3.Node.js示例代码:

js 复制代码
const express = require("express");
const app = express();
const PORT = 3000;

app.get("/", (req, res) => {
  res.send("Welcome come to learn Node.js!");
});

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

启动node.js项目后,访问点击这里即可

shell 复制代码
node app.js

三、Node.js基本语法库使用

1.用Node.js实现IO流以及基本服务的构建

js 复制代码
const path =require('path')
const fileSystem=require('fs')
//1.Use a callback function to obtain the reading result
fileSystem.readFile('./file/hello.txt','utf8',function(err,dataStr){
    if(err){
        console.log('File reading failed!',err.message);
        return
    }
    console.log('File read successful')
    console.log('As shown below');
    console.log(dataStr);
})
// path can also be displayed as follows:
// path.join(__dirname+'/file/hello.txt')
//__dirname is the absolute path of the current file
//2.write to file
fileSystem.writeFile('./file/learn.txt','37方寸你好',function(err){
    if(err){
        console.log('File write failed!',err.message);
        return
    }
    console.log('File write successful')
})
//3.read and write
fileSystem.readFile('./file/hero.txt', 'utf8', function (err, dataStr) {
    if (err) {
        return console.log('File reading failed!',err.message);
    }
    const tempArray = dataStr.split(' ')
    console.log(tempArray)
    const finalArray = []
    tempArray.forEach(item => {
        finalArray.push(item.replace('=', ':'))
    })
    // Linux中\n表示回车并换行;
    // Windows中\r\n表示回车并换行。
    // Mac中\r表示回车并换行。
    const newStr = tempArray.join('\r\n')
    console.log(newStr)
    fs.writeFile('./file/newHero.txt',newStr,function(err){
        if(err){
        return console.log('File write failed!',err.message);
        }
        console.log('File write successful')
    })
})
//4.create 'http' server
const http = require('http');
const server = http.createServer();
server.on('request', (req, res) => {
    const url = req.url;
    const method = req.method;
    const str = `The URL address you requested is ${url}.The requested method type is ${method}`;
    console.log(str);
    res.setHeader('Content-Type', 'text/html;charset=utf-8');
    res.end(str);
});
// Start the server and listen on port 3700
console.log('Attempting to start server...');
server.listen(3700, function () {
    console.log('server running at http://127.0.0.1:3700');
});

2.用Node.js定义通用方法

1.定义时间格式化的工具

js 复制代码
//Define the method of formatting time
function dateFormat(dtStr) {

    const dt = new Date(dtStr)
    const y = dt.getFullYear()
    const m = padZero(dt.getMonth() + 1)
    const d = padZero(dt.getDate())
    const hh = padZero(dt.getHours())
    const mm = padZero(dt.getMinutes())
    const ss = padZero(dt.getSeconds())
 
 // Format and return a datetime string in the format of "YYYY-MM-DD HH:MM:SS"
    return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
}
function padZero(n) {
    return n > 9 ? n : '0' + n
}
//export api
module.exports = {
    dateFormat
}

2.实际调用api

js 复制代码
//import timeFormat.js
const Time=require('./timeFormat')
const dt= new Date()
console.log(dt)
const newDate = Time.dateFormat(dt)
console.log(newDate)

总结

Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时环境,它让 JavaScript 突破了浏览器的限制,能够在服务器端运行。采用事件驱动和非阻塞 I/O模型,特别适合处理高并发的 I/O 密集型应用,如实时聊天、API 服务和微服务架构。通过丰富的 npm 生态系统和统一的 JavaScript 技术栈,Node.js 极大地提升了全栈开发效率,成为现代 Web 开发中连接前端与后端的重要桥梁。

相关推荐
IT_陈寒12 小时前
JavaScript开发者必看:5个让你的代码性能翻倍的隐藏技巧
前端·人工智能·后端
还是大剑师兰特13 小时前
Vue3 中 computed(计算属性)完整使用指南
前端·javascript·vue.js
井川不擦13 小时前
前端安全通信方案:RSA + AES 混合加密
前端
孜孜不倦不忘初心13 小时前
Ant Design Vue 表格组件空数据统一处理 踩坑
前端·vue.js·ant design
AD_wjk13 小时前
Android13系统集成方案
前端
Joyee69113 小时前
RN 的新通信模型 JSI
前端·react native
somebody13 小时前
零经验学 react 的第6天 - 循环渲染和条件渲染
前端
青晚舟13 小时前
AI 时代前端还要学 Docker & K8s 吗?我用一次真实部署经历说清楚
前端·github
墨鱼笔记13 小时前
不使用微前端:如何实现主应用和子模块动态管理与通信实现
前端
兆子龙13 小时前
前端工程师转型 AI Agent 工程师:后端能力补全指南
前端·javascript