Node.js 适配器
概览
Node.js 适配器是为 Node.js 环境设计的,提供了对云开发服务的访问能力。它允许开发者在 Node.js 应用中使用云开发的功能,如数据库、存储、函数等。
安装
使用 npm 安装 Node.js 适配器:
npm i @cloudbase/adapter-node
快速开始
使用
const cloudbase = require("@cloudbase/js-sdk");
const adapter = require("@cloudbase/adapter-node");
// 使用 Node.js 适配器
cloudbase.useAdapters(adapter);
const app = cloudbase.init({
env: "your-env", // 需替换为实际使用环境 id
});
使用示例
云函数调用示例
// 云函数调用示例
const result = await app.callFunction({
name: "your-function-name",
data: {
key: "value"
}
});
数据库操作示例
// 数据库操作示例
const db = app.database();
// 创建测试集合
const testCollection = db.collection('test_collection');
// 插入测试数据
const insertResult = await testCollection.add({
name: "Node.js 测试",
timestamp: new Date().toISOString(),
});
文件上传示例
// 上传文件示例
const fileName = `test-files/app-upload-${Date.now()}.jpg`;
const fs = require('fs');
const testFilePath = '/your/local/path/XXX.jpg'; // 替换为你的本地文件路径
// 读取文件内容
const fileBuffer = fs.readFileSync(testFilePath);
const uploadResult = await app.uploadFile({
cloudPath: fileName,
filePath: fileBuffer,
onUploadProgress: function (progressEvent) {
console.log("上传进度:", progressEvent);
var percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
}
});