为什么 Node.js 成为后端开发者的新宠

190 阅读2分钟

image.png

1. 认识 Node.js

Node.js 是一个基于 Chrome V8 引擎构建的开源、跨平台的 JavaScript 运行时环境,允许开发者在服务器端运行 JavaScript 代码。V8 引擎是谷歌公司开发的技术,旨在提高 JavaScript 的执行速度。通过 Node.js,开发者可以在服务器上处理用户在浏览器发起的各种请求。

2. 安装配置 Node.js

2.1 下载安装

访问 开发环境部署神器-Servbay 下载并安装。根据提示进行安装部署。

2.2 配置

  1. 根据 Servbay官网教程配置
  2. 配置 npm 依赖位置

3. Node.js 和 npm 的关系

npm(Node Package Manager)是随 Node.js 一起安装的包管理工具。开发 Node.js 应用时,开发者可以通过 npm 方便地安装和管理各种功能模块。例如,安装 axios:

npm install axios

npm 仓库地址:npmjs.com

4. 内置模块

学习 Node.js 主要是掌握其内置 API 和常用的第三方 API。以下是一些常用的内置模块:

4.1 文件操作: fs

fs 模块用于文件操作。

读文件

const fs = require('fs');
fs.readFile('./zhifou.txt', 'utf8', function (err, data) {if (err) {return console.log('读取失败!' + err.message);
  }console.log(data);
});

写文件

const fs = require('fs');
fs.writeFile('./hello.txt', '锄禾日当午,汗滴禾下土', function (err) {if (err) {return console.log('写入失败!' + err.message);
  }console.log('写入成功!');
});

4.2 路径操作:path

path 模块用于处理文件路径。

join

const path = require('path');
let finalPath = path.join('/a', '/b', '/c');
console.log(finalPath);

basename

const path = require('path');
const fpath = '/a/b/zhifou.js';
console.log("name1:", path.basename(fpath));
console.log("name2:", path.basename(fpath, '.js'));

extname

const path = require('path');
console.log("name:", path.extname('/a/b/zhifou.js'));

4.3 http

http 模块用于创建 Web 服务器。

const http = require('http');
const server = http.createServer();
server.on('request', (req, res) => {
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
  res.end(`请求的 URL 是 ${req.url}, 请求的方法类型是 ${req.method}`);
});
server.listen(8081, () => {console.log('server running at http://127.0.0.1:8081');
});

5. 模块化

5.1 Node.js 模块化

Node.js 遵循 CommonJS 模块化规范,一个文件就是一个模块,通过 require 加载模块,使用 exportsmodule.exports 来暴露模块内容。

5.2 ES6 模块化

ES6 模块化更好地与前端技术栈(如 React、Vue)整合。使用 importexport 关键字进行模块的导入和导出。

导出方式

  • 默认导出:
export default { name: "知否君", age: 23, desc: function() { console.log("公众号:知否技术"); } };
  • 统一导出:
export { name, age, desc };

导入方式

  • 默认导入:
import common from './common.js';
  • 解构赋值导入:
import { name, age } from './common.js';

6. 第三方 API

常用的第三方 API 包括 axios、pinia、vuex、mysql、express 等,具体根据需求进行学习。

7. Node.js 常见问题

  1. npm 是什么? npm 是一个包管理器,方便开发者安装和管理依赖包。
  2. Node.js 和 Vue 有什么联系? Vue 本身不依赖 Node.js,但 Vue 的脚手架(如 Vue CLI)和构建工具(如 Webpack)是基于 Node.js 开发的。
  3. Vite 和 Node.js 的关系? Vite 是一个前端构建工具,需要 Node.js 环境来运行。
  4. Node.js 和 npm 的关系? npm 是 Node.js 的包管理器,用于管理和安装依赖包。
  5. npm run dev 的本质 执行 npm run dev 启动开发服务器,提供服务并自动监听文件变化,提升开发效率。