napi-rs的使用

朱重迁 - Nov 5 - - Dev Community

安装 @napi-rs/cli

npm install -g @napi-rs/cli
Enter fullscreen mode Exit fullscreen mode

创建项目

napi new my-project
Enter fullscreen mode Exit fullscreen mode

写入以下内容到my-project/src/lib.rs文件:

#![deny(clippy::all)]

use image::codecs::png::{CompressionType, FilterType, PngEncoder};
use image::Luma;
use qrcode::{EcLevel, QrCode};
#[macro_use]
extern crate napi_derive;

#[napi]
pub fn sum(a: i32, b: i32) -> i32 {
  a + b
}

#[napi]
pub fn generate_qr_code(text: String) -> Result<Vec<u8>, napi::Error> {
  let qr = QrCode::with_error_correction_level(&text, EcLevel::L)
    .map_err(|e| napi::Error::new(napi::Status::Unknown, e.to_string()))?;
  let img_buf = qr.render::<Luma<u8>>().min_dimensions(200, 200).build();
  let mut encoded_buf = Vec::with_capacity(512);
  let encoder = PngEncoder::new_with_quality(
    &mut encoded_buf,
    CompressionType::Default,
    FilterType::NoFilter,
  );
  img_buf
    .write_with_encoder(encoder)
    .map_err(|e| napi::Error::new(napi::Status::Unknown, e.to_string()))?;
  Ok(encoded_buf)
}
Enter fullscreen mode Exit fullscreen mode

编译项目

cd my-project
npm run build
Enter fullscreen mode Exit fullscreen mode

使用项目

创建文件test.js

const express = require('express');
const utils = require('./index.js'); // 确保 index.js 中有 sum 和 generateQrCode 方法

const app = express();
const PORT = 3000;

// 设置一个 API 接口生成 QR 码
app.get('/qrcode', (req, res) => {
    try {
        const data = utils.generateQrCode('https://www.google.com');

        const buffer = Buffer.from(data);

        const base64Image = buffer.toString('base64');

        const dataUrl = `data:image/png;base64,${base64Image}`;

        res.json({ qrcode: dataUrl });
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: '生成 QR 码时出错' });
    }
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`服务正在运行,监听端口 ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

运行项目

node test.js
Enter fullscreen mode Exit fullscreen mode
.
Terabox Video Player