Spaces:
Sleeping
Sleeping
| const express = require('express'); | |
| const addon = require('./app_node_addon'); | |
| const app = express(); | |
| const PORT = process.env.PORT || 3000; | |
| app.use(express.json()); | |
| // 健康检查 | |
| app.get('/health', (req, res) => { | |
| res.json({ status: 'ok', service: 'node-napi' }); | |
| }); | |
| // 调用 N-API addon | |
| app.post('/api/napi/hello', (req, res) => { | |
| try { | |
| const { name } = req.body; | |
| const result = addon.hello(name || 'World'); | |
| res.json({ success: true, result }); | |
| } catch (error) { | |
| res.status(500).json({ success: false, error: error.message }); | |
| } | |
| }); | |
| // 调用 N-API addon 计算 | |
| app.post('/api/napi/add', (req, res) => { | |
| try { | |
| const { a, b } = req.body; | |
| if (typeof a !== 'number' || typeof b !== 'number') { | |
| return res.status(400).json({ | |
| success: false, | |
| error: '参数必须是数字' | |
| }); | |
| } | |
| const result = addon.add(a, b); | |
| res.json({ success: true, result }); | |
| } catch (error) { | |
| res.status(500).json({ success: false, error: error.message }); | |
| } | |
| }); | |
| // 复杂计算示例 | |
| app.post('/api/napi/compute', (req, res) => { | |
| try { | |
| const { numbers, operation } = req.body; | |
| if (!Array.isArray(numbers)) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'numbers 必须是数组' | |
| }); | |
| } | |
| let result; | |
| switch (operation) { | |
| case 'sum': | |
| result = numbers.reduce((acc, num) => acc + num, 0); | |
| break; | |
| case 'average': | |
| result = numbers.reduce((acc, num) => acc + num, 0) / numbers.length; | |
| break; | |
| default: | |
| return res.status(400).json({ | |
| success: false, | |
| error: '不支持的运算类型' | |
| }); | |
| } | |
| res.json({ success: true, result }); | |
| } catch (error) { | |
| res.status(500).json({ success: false, error: error.message }); | |
| } | |
| }); | |
| app.listen(PORT, () => { | |
| console.log(`Node.js N-API 服务运行在端口 ${PORT}`); | |
| }); |