Node.js Quick Start
This document introduces how to create a Node.js application from scratch and deploy it to CloudBase HTTP cloud functions.
Prerequisites
Before you begin, make sure you have:
- Have Node.js installed (v18 or later versions recommended)
- Have a Tencent Cloud account with CloudBase service activated
- Have basic knowledge of Node.js development
Step 1: Create a Project Directory
Create a new directory named helloworld and go to the directory:
mkdir helloworld
cd helloworld
Step 2: Initialize Project Configuration
Create a package.json file to describe project information and dependencies:
{
"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 Application Code
Create an index.js file in the same directory, which is the entry file of the application:
⚠️ Important Notice: The default port for CloudBase HTTP cloud function must be
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") {
// 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 (here using ipinfo.io as an example)
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 === "/health") {
// Health Check API
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): Obtain and return client IP information - Health Check (
/health): returns service status information - Error Handling: returns a 404 error for unknown paths
Step 4: Create a Startup Script
Create the scf_bootstrap file (without an extension), which is the startup script for CloudBase cloud functions:
#!/bin/bash
node index.js
⚠️ Caution:
- The file name must be
scf_bootstrapwithout extension- Ensure the file has execute permission
Grant execute permission to the startup script:
chmod +x scf_bootstrap
Step 5: Test Locally (Optional)
Test the application locally before deployment:
node index.js
After successful testing, you can verify in the following ways:
- Access
http://localhost:9000/to view the Hello World message - Access
http://localhost:9000/myipto view IP information - Access
http://localhost:9000/healthto view the health status
Press Ctrl + C to stop the local server.
Step 6: Deploy to CloudBase HTTP Cloud Function
Prepare Deployment Files
Ensure your project directory contains the following files:
helloworld/
|-- scf_bootstrap
├── package.json
└── index.js
Deploy via the Console
- Log in to the CloudBase Console
- Select your environment and go to the [Cloud Function] page
- Click [New Cloud Function]
- Select [HTTP cloud function]
- Fill in the function name (for example:
helloworld) - Select runtime: Node.js 18.x
- Select the [Local upload] method
- Package the project files into a zip file and upload it
- Click [OK] to complete the deployment
Deploy via CLI (Coming Soon)
Package the Project
If you need to package manually, you can use the following command:
# Create zip package
zip -r helloworld.zip package.json index.js
Step 7: Access Your Application
After successful deployment, you can refer to Web Client Invocation to configure custom domain access for
You can test in the following ways:
- Access the root path to view the Hello World message
- Access the
/myippath to view IP information - Access the
/healthpath to check the service status
Frequently Asked Questions
Q: Why must I use port 9000?
A: The CloudBase HTTP cloud function requires the application to listen on port 9000, which is the standard configuration of the platform.
Q: How do I view function logs?
A: On the CloudBase console's cloud function page, click the function name to go to the details page and view the running logs.
Q: Which Node.js versions are supported?
A: CloudBase supports Node.js versions such as 12.x, 14.x, 16.x, 18.x, etc. It is recommended to use the latest LTS version.
Q: How do I handle CORS cross-origin issues?
A: Set CORS-related headers such as Access-Control-Allow-Origin in the response headers, as shown in the example code.
Q: How to handle long cold startup times for functions?
A: Cold startup time can be reduced by methods such as warm-up mechanisms, reducing dependency package size, and optimizing code logic.
Best Practices
- Error Handling: Always add proper error handling for asynchronous operations
- Response Header Settings: Set response headers properly, including Content-Type and other necessary headers.
- Logging: Use
console.logto log key information for easier debugging. - Environment Variables: Use
process.envto manage configuration information - Code Structure: For complex applications, it is recommended to use frameworks such as Express.js.
Next Steps
- Learn more about HTTP cloud function configuration options
- Learn how to Add Database Operations
- See Express.js framework integration