Node.js 快速开始
本文档介绍如何从零开始创建一个 Node.js 应用,并将其部署到 CloudBase HTTP 云函数中。
前置条件
在开始之前,请确保您已经:
- 安装了 Node.js (推荐 v18 或更高版本)
- 拥有腾讯云账号并开通了 CloudBase 服务
- 了解基本的 Node.js 开发知识
第一步:创建项目目录
创建名为 helloworld 的新目录,并进入该目录:
mkdir helloworld
cd helloworld
第二步:初始化项目配置
创建 package.json 文件,用于描述项目信息和依赖关系:
{
"name": "helloworld",
"description": "Simple hello world sample in Node",
"version": "1.0.0",
"type": "module",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"author": "Tencent CloudBase",
"license": "Apache-2.0"
}
第三步:编写应用代码
在同一目录中创建 index.js 文件,这是应用的入口文件:
⚠️ 重要提示:CloudBase HTTP 云函数的默认端口必须是
9000。
import { createServer } from "node:http";
import { Readable } from "node:stream";
const server = createServer(async (req, res) => {
if (req.url === "/") {
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
res.end("Hello World!");
} else if (req.url === "/myip") {
// 设置 CORS 头,允许跨域请求
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Content-Type", "application/json");
try {
// 使用 fetch 获取远程数据(这里使用 ipinfo.io 作为示例)
const response = await fetch("https://ipinfo.io", {
headers: {
Accept: "application/json",
},
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
Readable.fromWeb(response.body).pipe(res);
} catch (error) {
console.error("获取 IP 信息失败:", error);
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({
error: "Failed to fetch remote data",
message: error.message
}));
}
} else if (req.url === "/health") {
// 健康检查接口
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({
status: "healthy",
timestamp: new Date().toISOString(),
version: "1.0.0"
}));
} else {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "Not Found" }));
}
});
const port = 9000;
const host = "0.0.0.0";
server.listen(port, host, () => {
console.log(`Server running at http://localhost:${port}/`);
console.log(`Try accessing http://localhost:${port}/myip to see your IP info`);
console.log(`Health check available at http://localhost:${port}/health`);
});
此代码创建了一个基本的 Web 服务器,提供以下功能:
- 根路径 (
/):返回 "Hello World!" 消息 - IP 查询 (
/myip):获取并返回客户端 IP 信息 - 健康检查 (
/health):返回服务状态信息 - 错误处理:对于未知路径返回 404 错误
第四步: 创建启动脚本
创建 scf_bootstrap 文件(无扩展名),这是 CloudBase 云函数的启动脚本:
#!/bin/bash
node index.js
⚠️ 注意:
- 文件名必须是
scf_bootstrap,没有扩展名- 确保文件具有执行权限
为启动脚本添加执行权限:
chmod +x scf_bootstrap
第五步:本地测试(可选)
在部署之前,您可以在本地测试应用:
node index.js
测试成功后,您可以通过以下方式验证:
- 访问
http://localhost:9000/查看 Hello World 消息 - 访问
http://localhost:9000/myip查看 IP 信息 - 访问
http://localhost:9000/health查看健康状态
按 Ctrl + C 停止本地服务器。
第六步:部署到 CloudBase HTTP 云函数
准备部署文件
确保您的项目目录包含以下文件:
helloworld/
|-- scf_bootstrap
├── package.json
└── index.js
通过控制台部署
- 登录 CloudBase 控制台
- 选择您的环境,进入「云函数」页面
- 点击「新建云函数」
- 选择「HTTP 云函数」
- 填写函数名称(如:
helloworld) - 选择运行时:Node.js 18.x
- 选择「本地上传」方式
- 将项目文件打包为 zip 文件并上传
- 点击「确定」完成部署
通过 CLI 部署(敬请期待)
打包项目
如果需要手动打包,可以使用以下命令:
# 创建 zip 包
zip -r helloworld.zip package.json index.js scf_bootstrap
第七步:访问您的应用
部署成功后,您可以参考Web 客户端调用设置自定义域名访问HTTP 云函数。
您可以通过以下方式测试:
- 访问根路径查看 Hello World 消息
- 访问
/myip路径查看 IP 信息 - 访问
/health路径查看服务状态
常见问题
Q: 为什么必须使用 9000 端口?
A: CloudBase HTTP 云函数要求应用监听 9000 端口,这是平台的标准配置。
Q: 如何查看函数日志?
A: 在 CloudBase 控制台的云函数页面,点击函数名称进入详情页,可以查看运行日志。
Q: 支持哪些 Node.js 版本?
A: CloudBase 支持 Node.js 12.x、14.x、16.x、18.x 等版本,建议使用最新的 LTS 版本。
Q: 如何处理 CORS 跨域问题?
A: 在响应头中设置 Access-Control-Allow-Origin 等 CORS 相关头部,如示例代码所示。
Q: 函数冷启动时间较长怎么办?
A: 可以通过预热机制、减少依赖包大小、优化代码逻辑等方式来减少冷启动时间。
最佳实践
- 错误处理:始终为异步操作添加适当的错误处理
- 响应头设置:正确设置 Content-Type 和其他必要的响应头
- 日志记录:使用
console.log记录关键信息,便于调试 - 环境变量:使用
process.env管理配置信息 - 代码结构:对于复杂应用,建议使用 Express.js 等框架
下一步
- 了解更多 HTTP 云函数配置选项
- 学习如何 添加数据库操作
- 查看 Express.js 框架集成