当前位置: 首页 > news >正文

Nodejs学习

Node.js 是一个基于 Chrome V8 JavaScript 引擎构建的 JavaScript 运行时环境。简单来说,Node.js 让 JavaScript 可以在服务器端运行,而不仅仅局限于浏览器中。

创建第一个 Node.js 项目

在项目文件夹执行npm init -y

会出现package.json

然后新建app.js

输入测试代码:

const http = require('http');const server = http.createServer((req,res)=>{res.statusCode = 200;res.setHeader('Content-Type','text/plain');res.end('RUNOOB Node Test ~ hello,Node js\n');
});const port = 3000;
server.listen(port,()=>{console.log(`服务器运行地址:http://localhost:${port}/`);
})

访问3000,打印了

Nodejs包含哪几部分

1.使用 require 指令来加载和引入模块

const module = require('module-name');

2.创建服务器

使用http.createServer()创建,

listen方法监听

函数通过request,response接收和响应

简便写法:

var http = require('http');http.createServer(function (request, response) {response.writeHead(200, {'Content-Type': 'text/plain'});response.end('Hello World\n');
}).listen(8888);console.log('Server running at http://127.0.0.1:8888/');

Nodejs路由控制

const http = require('http');const server = http.createServer((req,res)=>{if(req.url === '/'){res.writeHead(200,{"content-type":'text/plain'});res.end("welcome ");}else if(req.url === '/about'){res.writeHead(200,{"content-type":'text/plain'});res.end("about");}else{res.writeHead(404,{"content-type":'text/plain'});res.end('404 Not Found');}
});const port = 3000;
server.listen(port,()=>{console.log(`服务器运行地址:http://localhost:${port}/`);
})

node实现打包工具webpack

蓝桥杯要求手写一个 Webpack,这是一道考察前端构建原理的综合题。

Webpack 本质是一个模块打包工具,它的核心工作流程包括:

  1. 解析入口文件:从入口文件开始,递归分析所有依赖。
  2. 构建依赖图:记录每个模块的依赖关系和源代码。
  3. 转换模块代码:通过 Loader 处理不同类型的文件(如 CSS、图片)。
  4. 打包输出:将所有模块合并为一个或多个 bundle 文件。
const fs = require('fs');
const path = require('path');
const babel = require('@babel/core');class MyWebpack {constructor(config) {this.config = config;this.entry = config.entry; // 入口文件路径this.output = config.output; // 输出配置this.modules = []; // 存储所有模块信息}// 启动打包run() {this.buildModule(this.entry, true);this.emitFiles();}// 构建模块buildModule(filename, isEntry) {const moduleId = './' + path.relative(process.cwd(), filename);const source = fs.readFileSync(filename, 'utf-8');const { dependencies, transformedSource } = this.parseModule(source, filename);const module = {id: moduleId,filename,dependencies,source: transformedSource};this.modules.push(module);// 递归处理依赖dependencies.forEach(dep => {this.buildModule(path.join(path.dirname(filename), dep));});return module;}// 解析模块:转换代码并提取依赖parseModule(source, filename) {const dependencies = [];// 使用 Babel 转换 ES6+ 代码为 CommonJS 格式const { code } = babel.transformSync(source, {presets: ['@babel/preset-env'],plugins: [[// 自定义插件:分析 import 语句收集依赖function() {return {visitor: {ImportDeclaration(path) {dependencies.push(path.node.source.value);}}};}]]});return { dependencies, transformedSource: code };}// 生成输出文件emitFiles() {const outputPath = path.join(this.output.path, this.output.filename);// 创建模块映射函数const modules = this.modules.reduce((acc, module) => {acc[module.id] = `function(module, exports, require) {${module.source}}`;return acc;}, {});// 生成自执行的 bundle 代码const bundle = `(function(modules) {// 模块缓存const installedModules = {};// 自定义 require 函数function require(id) {if (installedModules[id]) {return installedModules[id].exports;}const module = installedModules[id] = {exports: {},id: id,loaded: false};// 执行模块函数modules[id].call(module.exports,module,module.exports,require);module.loaded = true;return module.exports;}// 从入口模块开始执行return require('${this.entry}');})({${Object.entries(modules).map(([id, fn]) => `"${id}": ${fn}`).join(',')}});`;// 写入输出文件fs.writeFileSync(outputPath, bundle);console.log(`Bundle created at ${outputPath}`);}
}module.exports = MyWebpack;

使用express构建node项目

1.npm install express

2.npx express-generator,就自动创建好了

3.基本路由

  • app is an instance of express.
  • METHOD is an HTTP request method, in lowercase.
  • PATH is a path on the server.
  • HANDLER is the function executed when the route is matched.

app.method('path',handler) 

app.get('/', (req, res) => {res.send('Hello World!')
})

4.利用 Express 托管静态文件

为了提供诸如图像、CSS 文件和 JavaScript 文件之类的静态文件,请使用 Express 中的 express.static 内置中间件函数。

此函数特征如下:

express.static(root, [options])

例如,通过如下代码就可以将 public 目录下的图片、CSS 文件、JavaScript 文件对外开放访问:

app.use(express.static('public'))

现在,你就可以访问 public 目录中的所有文件了:

http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html

要为 express.static 函数服务的文件创建虚拟路径前缀(该路径在文件系统中不存在),请为静态目录指定挂载路径,如下所示:

<span style="background-color:#f7f7f7"><span style="color:black"><code class="language-javascript">app<span style="color:#999999">.</span><span style="color:#dd4a68">use<span style="color:#999999">(</span></span><span style="color:#669900">'/static'</span><span style="color:#999999">,</span> express<span style="color:#999999">.</span><span style="color:#0077aa">static</span><span style="color:#999999">(</span><span style="color:#669900">'public'</span><span style="color:#999999">)</span><span style="color:#999999">)</span>
</code></span></span>

现在,你就可以通过带有 /static 前缀地址来访问 public 目录中的文件了。

http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html

 更多例子Express examples

http://www.lryc.cn/news/624936.html

相关文章:

  • 基于ssm jsp中学校园网站源码和答辩PPT论文
  • 视觉语言导航(11)——预训练范式 4.1
  • 封装、继承、多态的含义及其项目应用
  • 机器人技术核心模块与前沿趋势总结
  • TikTok墨西哥POP店今日正式开放!0佣金+流量扶持+5店开放
  • PG靶机 - Bratarina
  • C# NX二次开发:字符串控件StringBlock讲解
  • Pandas 中常用的统计计算、排序、分组聚合
  • plantsimulation知识点25.8.18-从一个RGV到另一台RGV,工件长度和宽度方向互换
  • 【牛客刷题】计算1到n最低位1代表的数字之和
  • Layui COP证书管理系统
  • 《Image Classification with Classic and Deep Learning Techniques》复现
  • 吴恩达 Machine Learning(Class 1)
  • cross-env 与 @nestjs/config 的对比分析
  • 小杰机械视觉(one day)——基础阶段结束,进入机械学习阶段。
  • leetcode43. 字符串相乘
  • TEST_
  • 10CL016YF484C8G Altera FPGA Cyclone
  • 视觉语言导航(8)——任务驱动的架构增强 3.3
  • 矿物分类案例(二)数据填充后使用6种模型训练
  • Android中flavor的使用
  • PostgreSQL中的json_agg()
  • 初始向量数据库之Milvus
  • milvus如何存储特殊类型的数据
  • Milvus向量数据库安装步骤
  • 大厂 | 华为半导体业务部2026届秋招启动
  • 【大模型】RAG
  • 基于nvm安装管理多个node.js版本切换使用(附上详细安装使用图文教程+nvm命令大全)
  • ANSI终端色彩控制知识散播(I):语法封装(Python)——《彩色终端》诗评
  • 楼宇自控系统深化设计需关注哪些核心要点?技术与应用解析