Node.js v24发布,你还未体验的新功能

6,189 阅读5分钟

4月30号,Node.js v18结束生命周期。
5月6日,Node.js v24发布。

技术应该不断迭代向前进,追求更高、更快、更强,对开发者更加友好。

但软件、框架新版本发布很难再令人心动,一是因为平时工作用不到哇,二是开发者只给只给文字描述不给演示案例啊喂,可能存在大大小小个未曾探索的坑。

Node.js 2009年出道,2025年了16岁,挑出一些实用功能进行体验测试。

图片.png

一、 文件监听实时运行 --watch

语法:node --watch 文件名 保存即所见,有点像Live Server插件的感觉。

保存即运行.gif

二、环境变量原生支持 --env-file

我理解的是创建.env文件写上配置参数,Node.js无需第三方库dotenv可直接读取变量值? 多次测试是失败的(通过其他项目Trae找到了正确的方法 附录2)。

针对Node.js新版本(v20.6+)的环境变量管理优化,我们可以使用Node.js原生支持的 --env-file 参数替代dotenv

在终端运行一定要记得带上参数,同时创建文件目录 node --env-file .env 文件名 图片.png

三、原生全局支持请求fetch()

前后端调用的写法一致性,Axios库受到冲击。Node.js甚至连模块都不需要引入。

95a6e7bc86d24de0bf16a27394819f3b~tplv-73owjymdk6-jj-mark-v1_0_0_0_0_5o6Y6YeR5oqA5pyv56S-5Yy6IEAg55m-5LiH5YmN56uv5ZCR5YmN5Yay_q75.webp

天气查询项目,Node.js发起fetch请求,关键调用代码。简洁多了!🐤🐤🐤 fc98468c3342432c92c8ad801db19e2c~tplv-73owjymdk6-jj-mark-v1_0_0_0_0_5o6Y6YeR5oqA5pyv56S-5Yy6IEAg55m-5LiH5YmN56uv5ZCR5YmN5Yay_q75.webp

四、多文件测试 --test

语法:node --test 文件名1 文件名2 测试正确的代码: 图片.png

测试存在错误的代码: 图片.png

五、 彩色控制台

现在Node.js内置模块util,可以直接使用styleText(样式关键字, 内容) 进行个性化彩色控制台输出。

图片.png

特别注意嵌套多个样式的写法,可以考虑自定义递归函数:
console.log(styleText('italic', styleText('bold', styleText('blue', '蓝色加粗斜体'))));

4.1 七彩控制台实用效果 5月13日 New

自定义函数 封装 console.log()控制台打印语句 ,为生活增添彩色乐趣。

图片.png

function co(文本内容){
    // 定义随机背景颜色组(移除分号)
    const colorArr = ['bgBlack', 'bgRed', 'bgGreen', 'bgYellow', 'bgBlue', 'bgMagenta', 'bgCyan', 'bgWhite', 'bgGray', 'bgRedBright', 'bgGreenBright', 'bgYellowBright', 'bgBlueBright', 'bgMagentaBright', 'bgCyanBright', 'bgWhiteBright']
    
    const fontColorArr = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'gray', 'redBright', 'greenBright', 'yellowBright', 'blueBright', 'magentaBright', 'cyanBright', 'whiteBright']

    // 修改:将Emoji表情加载到数组中并保持一行
    const emojiArr = ['🌰','🌱','🌲','🌳','🌴','🌵','🌷','🌸','🌹','🌺','🌻','🌼','🌽','🌾','🌿','🍀','🍁','🍂','🍃','🍄','🍅','🍆','🍇','🍈','🍉','🍊','🍋','🍌','🍍','🍎','🍏','🍐','🍑','🍒','🍓','🍔','🍕','🍖','🍗','🍘','🍙','🍚','🍛','🍜','🍝','🍞','🍟','🍠','🍡','🍢','🍣','🍤','🍥','🍦','🍧','🍨','🍩','🍪','🍫','🍬','🍭','🍮','🍯','🍰','🍱','🍲','🍳','🍴','🍵','🍶','🍷','🍸','🍹','🍺','🍻','🍼','🍾','🍿','🎀','🎁','🎂']
    // 生成随机索引(移除分号)
    const i = Math.floor(Math.random() * fontColorArr.length)
    const j = Math.floor(Math.random() * emojiArr.length)
    // 获取随机背景颜色(移除分号)
    const 背景颜色 = fontColorArr[i]
    let 内容 = `${emojiArr[j].repeat(3)}  ${文本内容}`
    console.log(styleText( 背景颜色,内容 ))  // 移除分号并简化空格
}//信息处理

co彩色123.gif

六、客户端内置WebSocket

原以为服务端和客户端都可以不再引入Websocket库 ws,测试了半天才发现只有客户端省去了,似乎有点鸡肋。 如果我的理解有误请指教。

图片.png

七、常见错误及原因

1、util._extend 出错

(node:35876) [DEP0060] DeprecationWarning: The util._extend API is deprecated. Please use Object.assign() instead. (Use node --trace-deprecation ... to show where the warning was created)

因为引用的代码库中使用了 util._extend 已弃用​:该 API 原本用于对象属性合并

// 弃用写法
const util = require('util');
const merged = util._extend({}, obj1, obj2);

// 正确写法(无需引入 util)
const merged = Object.assign({}, obj1, obj2);

附录

1.安装Node.js v24

图片.png

图片.png

安装包含:

  • Node.js运行时 3102KB 安装Node.js核心运行时(Node.exe)
  • 24KB Node.js通用的包管理器
  • 1116KB Node.js推荐的包管理工具
  • 1KB 在线文档快捷方式,在开始菜单添加进入Node.js在线文档和网站的连接
  • 2KB 添加Node.js,npm和 modules 全局安装PATH环境变量。

图片.png

Chocolatey是 windows 下一款命令行包管理软件 ,简单说这就是 Windows 的 apt-get。选择不装。

在命令行查看Node.js和npm版本 图片.png

注:安装Node.js不需要重启电脑即可生效。

2. 使用--env-file 原生读取.env自定义环境变量

图片.png

3. 彩色控制台代码

const { styleText } = require('util'); 


// 1. 文本样式测试
console.log('\n=== 文本样式测试 ===');
console.log(styleText('reset', '重置样式'));
console.log(styleText('bold', '加粗文本'));
console.log(styleText('dim', '暗淡文本')); 
console.log(styleText('italic', '斜体文本'));
console.log(styleText('underline', '下划线文本'));
console.log(styleText('blink', '闪烁文本'));
console.log(styleText('inverse', '反转颜色'));
console.log(styleText('hidden', '隐藏文本'));
console.log(styleText('strikethrough', '删除线'));
console.log(styleText('doubleunderline', '双下划线'));
console.log(styleText('framed', '边框文本'));
console.log(styleText('overlined', '上划线文本'));

// 2. 文本颜色测试
console.log('\n=== 文本颜色测试 ===');
console.log(styleText('black', '黑色文本'));
console.log(styleText('red', '红色文本'));
console.log(styleText('green', '绿色文本'));
console.log(styleText('yellow', '黄色文本')); 
console.log(styleText('blue', '蓝色文本'));
console.log(styleText('magenta', '品红色文本'));
console.log(styleText('cyan', '青色文本'));
console.log(styleText('white', '白色文本'));
console.log(styleText('gray', '灰色文本'));
console.log(styleText('redBright', '亮红色文本'));
console.log(styleText('greenBright', '亮绿色文本'));
console.log(styleText('yellowBright', '亮黄色文本'));
console.log(styleText('blueBright', '亮蓝色文本'));
console.log(styleText('magentaBright', '亮品红色文本'));
console.log(styleText('cyanBright', '亮青色文本'));
console.log(styleText('whiteBright', '亮白色文本'));

// 3. 背景颜色测试  
console.log('\n=== 背景颜色测试 ===');
console.log(styleText('bgBlack', '黑色背景'));
console.log(styleText('bgRed', '红色背景'));
console.log(styleText('bgGreen', '绿色背景'));
console.log(styleText('bgYellow', '黄色背景'));
console.log(styleText('bgBlue', '蓝色背景'));
console.log(styleText('bgMagenta', '品红色背景'));
console.log(styleText('bgCyan', '青色背景'));
console.log(styleText('bgWhite', '白色背景')); 
console.log(styleText('bgGray', '灰色背景'));
console.log(styleText('bgRedBright', '亮红色背景'));
console.log(styleText('bgGreenBright', '亮绿色背景'));
console.log(styleText('bgYellowBright', '亮黄色背景'));
console.log(styleText('bgBlueBright', '亮蓝色背景'));
console.log(styleText('bgMagentaBright', '亮品红色背景'));
console.log(styleText('bgCyanBright', '亮青色背景'));
console.log(styleText('bgWhiteBright', '亮白色背景'));

// 4. 组合样式测试
console.log('\n=== 组合样式测试 ===');
// console.log(styleText('red.bold', '红色加粗文本'));
console.log(styleText('underline', styleText('bgYellow', '黄色背景带下划线')));
console.log(styleText('italic', styleText('bold', styleText('blue', '蓝色加粗斜体'))));
console.log(styleText('bgRed', styleText('greenBright', '亮绿色文本红色背景')));
console.log(styleText('inverse', styleText('magenta', '品红色反转样式')));
console.log(styleText('strikethrough', styleText('cyan', '青色删除线文本')));
console.log(styleText('bold', styleText('bgBlue', styleText('whiteBright', '亮白色加粗蓝色背景'))));

4.WebSocket代码

服务器端

const WebSocket = require('ws');

// 创建 WebSocket 服务器
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
  console.log('新的客户端连接');
  
  // 接收消息
  ws.on('message', (message) => {
    console.log('收到消息:', message.toString());
    
    // 广播给所有客户端
    wss.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(`服务器收到: ${message}`);
      }
    });
  });

  // 连接关闭
  ws.on('close', () => {
    console.log('客户端断开连接');
  });
});

console.log('WebSocket 服务器运行在 ws://localhost:8080');

客户端

// 使用Node.js 22+原生WebSocket(注意API差异)
const ws = new WebSocket('ws://localhost:8080');

// 使用addEventListener替代.on方法
ws.addEventListener('open', () => {
  console.log('已连接到服务器');
  ws.send('你好,服务器!');
});

ws.addEventListener('message', ({ data }) => {
  console.log('收到服务器消息:', data.toString());
});

ws.addEventListener('close', () => {
  console.log('连接已关闭');
});