温馨提示×

debian nodejs怎么连接库

小樊
47
2026-09-13 18:11:43
栏目: 编程语言

在 Debian 上用 Node.js“连接库”一般分几种常见场景,我按最常见的情况给你说明,你看看是哪一类:


一、连接【系统动态库(.so)】(比如 C/C++ 库)

1. 安装依赖库(Debian)

sudo apt update
sudo apt install libxxx-dev

例如:

sudo apt install libssl-dev

2. Node.js 中通过 ffi-napi 或 node-gyp 调用

方式一:使用 ffi-napi(简单)

npm install ffi-napi ref-napi

示例:

const ffi = require('ffi-napi');

const lib = ffi.Library('libm', {
  ceil: ['double', ['double']]
});

console.log(lib.ceil(4.2));

方式二:写原生插件(node-gyp)

npm install -g node-gyp
npm install nan

binding.gyp:

{
  "targets": [{
    "target_name": "addon",
    "sources": ["addon.cc"],
    "libraries": ["-lxxx"]
  }]
}

二、连接【数据库】(最常见)

1. MySQL

sudo apt install default-mysql-server
npm install mysql2
const mysql = require('mysql2');

const conn = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'test'
});

conn.query('SELECT 1', (err, res) => {
  console.log(res);
});

2. PostgreSQL

sudo apt install postgresql
npm install pg
const { Pool } = require('pg');
const pool = new Pool({
  user: 'postgres',
  host: 'localhost',
  database: 'test',
  password: 'password',
  port: 5432
});

pool.query('SELECT NOW()', (err, res) => {
  console.log(res.rows);
});

3. Redis

sudo apt install redis-server
npm install redis
const redis = require('redis');
const client = redis.createClient();

client.on('connect', () => {
  console.log('connected');
});

三、连接【Node.js 第三方模块(npm 包)】

npm install lodash
const _ = require('lodash');

四、常见问题(Debian 特有)

1. Node 版本太旧

Debian 自带 Node 可能很老:

node -v

建议用 nvm:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
nvm install 20

2. 找不到 .so 文件

ldconfig

或运行时指定:

LD_LIBRARY_PATH=/usr/local/lib node app.js

如果你能具体说一下:

  • 是 数据库 / C库 / 硬件库 / SDK
  • Debian 版本
  • Node 版本

我可以直接给你一份可运行的示例。

0 踩