Node.js Quick Start
This document describes how to create a Node.js application from scratch and deploy it to a CloudBase HTTP cloud function.
Prerequisites
Before you begin, ensure that you have:
- Installed Node.js (v18 or later is recommended)
- Have a Tencent Cloud account and have activated the CloudBase service
- Have a basic knowledge of Node.js development
Step 1: Create the project directory
Create a new directory named helloworld and enter the directory:
mkdir helloworld
cd helloworld
Step 2: Initialize Project Configuration
Create a package.json file to describe project information and dependencies. You can quickly initialize the project configuration by running npm init -y.
{
"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"
}
Step 3: Write the Application Code
Create an index.js file in the same directory, which is the entry file of the application:
⚠️ Important: CloudBase HTTP cloud functions must use the default port
9000.
import { createServer } from "node:http";
import { Readable } from "node:stream";
const server = createServer(async (req, res) => {
if (req.url.split('?')[0] === "/") {
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
res.end("Hello World!");
} else if (req.url.split('?')[0] === "/myip") {
// Set CORS headers to allow cross-origin requests
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Content-Type", "application/json");
try {
// Use fetch to obtain remote data (using ipinfo.io as an example here)
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("Failed to obtain IP information:", 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.split('?')[0] === "/health") {
// Health Check Endpoint
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`);
});
This code creates a basic Web server that provides the following features:
- Root path (
/): returns "Hello World!" message - IP Query (
/myip): obtains and returns the client's IP information - Health Check (
/health): returns service status information - Error Handling: returns 404 error for unknown paths
In addition to using the native Node.js http module, you can also use the @cloudbase/functions-framework for a more streamlined development experience. For more details, see Functions Framework Quick Start.