本教程介绍如何在 Databricks Apps 中创建简单的 Node.js 应用,该应用使用 Chart.js 和 Express 为网页提供动态图表。 该应用包括:
- 一个具有样式化设计并呈现图表的主页
- 返回模拟时序销售数据的 API 终结点
- 使用环境变量的动态端口
先决条件
完成本教程之前:
- 确保正确配置 Azure Databricks 工作区和本地开发环境。 请参阅 设置 Databricks Apps 工作区和开发环境。
- 创建自定义 Databricks 应用,用作 Node.js 代码的容器。 请参阅 创建自定义 Databricks 应用。
步骤 1:安装依赖项
打开终端并运行以下命令来:
- 安装 Node.js
- 为应用的源和配置文件创建本地目录
- 安装 Express
brew install node
mkdir my-node-app
cd my-node-app
npm install express
步骤 2:定义应用逻辑
创建一个名为app.js的文件,其内容如下:
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
const app = express();
const port = process.env.PORT || 8000;
const __dirname = path.dirname(fileURLToPath(import.meta.url));
app.use('/static', express.static(path.join(__dirname, 'static')));
// Serve chart page
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'static/index.html'));
});
// Serve mock time-series data
app.get('/data', (req, res) => {
const now = Date.now();
const data = Array.from({ length: 12 }, (_, i) => ({
date: new Date(now - i * 86400000).toISOString().slice(0, 10),
sales: Math.floor(Math.random() * 1000) + 100,
})).reverse();
res.json(data);
});
app.listen(port, () => {
console.log(`🚀 App running at http://localhost:${port}`);
});
此代码创建一个 Express 服务器,该服务器:
- 从
/static目录中提供 HTML 页 - 使用模拟销售数据响应
/data - 侦听
PORT环境变量定义的端口(或默认为 8000)
步骤 3:添加静态 HTML 文件
请在 static/index.html 处创建一个文件,该文件加载 Chart.js 并呈现折线图。 图表会自动从 /data API 提取模拟数据,并将其呈现在浏览器中。
<!DOCTYPE html>
<html>
<head>
<title>Sales Dashboard</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body {
font-family: sans-serif;
padding: 2rem;
}
canvas {
max-width: 100%;
height: 400px;
}
</style>
</head>
<body>
<h1>📈 Sales Dashboard</h1>
<canvas id="salesChart"></canvas>
<script>
async function renderChart() {
const response = await fetch('/data');
const data = await response.json();
const ctx = document.getElementById('salesChart').getContext('2d');
new Chart(ctx, {
type: 'line',
data: {
labels: data.map((d) => d.date),
datasets: [
{
label: 'Daily Sales',
data: data.map((d) => d.sales),
borderWidth: 2,
fill: false,
},
],
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true,
},
},
},
});
}
renderChart();
</script>
</body>
</html>
步骤 4:定义依赖项
创建一个 package.json 文件,该文件将 Express 声明为依赖项并设置启动脚本:
{
"name": "databricks-chart-app",
"version": "1.0.0",
"type": "module",
"main": "app.js",
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "^4.19.2"
}
}
步骤 5:在本地运行应用
若要在本地测试应用,请运行以下命令:
npm install
npm run start
导航到 http://localhost:8000 以查看过去 12 天内的模拟销售数据动态图表。
后续步骤
- 部署应用。 请参阅 部署 Databricks 应用。
- 将模拟数据替换为 Unity 目录或外部 API 中的数据。
- 添加 UI 筛选器,例如日期范围或产品类别。
- 使用 Azure Databricks 机密或 OAuth 保护应用。