在 Ubuntu 上用 Node.js 连接“库”,需要先明确你说的“库”是哪一种,常见有下面几类。我按最常见场景给你说明,并给出示例。
如果你指的是 C/C++ 动态库(如 libxxx.so),Node.js 通常通过 FFI 或 C++ Addon 来连接。
ffi-napi(推荐,简单)适合调用已有的 .so 库。
sudo apt update
sudo apt install -y nodejs npm
sudo apt install -y libffi-dev
mkdir demo && cd demo
npm init -y
npm install ffi-napi ref-napi
libm.soconst ffi = require('ffi-napi');
const ref = require('ref-napi');
const libm = ffi.Library('libm', {
sqrt: ['double', ['double']]
});
console.log(libm.sqrt(9)); // 3
✅ 适合:已有 .so 库,不想写 C++
❌ 不适合:复杂对象、高性能场景
适合高性能、复杂库。
npm install -g node-gyp
sudo apt install build-essential
然后写 .cc 文件并用 node-gyp 编译。
如果你指的是数据库(MySQL / PostgreSQL / MongoDB 等):
npm install mysql2
const mysql = require('mysql2/promise');
(async () => {
const conn = await mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456',
database: 'test'
});
const [rows] = await conn.execute('SELECT 1 + 1 AS result');
console.log(rows);
})();
npm install pg
const { Client } = require('pg');
const client = new Client({
host: 'localhost',
user: 'postgres',
password: '123456',
database: 'test'
});
await client.connect();
const res = await client.query('SELECT 1');
console.log(res.rows);
npm install mongodb
const { MongoClient } = require('mongodb');
const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
const db = client.db('test');
const col = db.collection('users');
console.log(await col.find().toArray());
如果你只是想“连接/使用库”:
npm install lodash
const _ = require('lodash');
console.log(_.chunk([1,2,3,4], 2));
ldconfig -p | grep libxxx
node -v
建议:
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
你可以直接告诉我:
.so 动态库?我可以给你 完整可运行的示例。