File size: 1,942 Bytes
dc21909
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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}`);
});