Skip to main content

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_bootstrap without 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/myip to view IP information
  • Access http://localhost:9000/health to 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

  1. Log in to the CloudBase Console
  2. Select your environment and go to the [Cloud Function] page
  3. Click [New Cloud Function]
  4. Select [HTTP cloud function]
  5. Fill in the function name (for example: helloworld)
  6. Select runtime: Node.js 18.x
  7. Select the [Local upload] method
  8. Package the project files into a zip file and upload it
  9. 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 /myip path to view IP information
  • Access the /health path 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

  1. Error Handling: Always add proper error handling for asynchronous operations
  2. Response Header Settings: Set response headers properly, including Content-Type and other necessary headers.
  3. Logging: Use console.log to log key information for easier debugging.
  4. Environment Variables: Use process.env to manage configuration information
  5. Code Structure: For complex applications, it is recommended to use frameworks such as Express.js.

Next Steps