如何用Node.js连接Memgraph及搭建该应用的测试环境?
用Node.js连接Memgraph的最简方案及测试环境快速搭建
一、最快搭建Memgraph测试环境
直接用Docker跳过复杂的手动安装流程:
- 拉取Memgraph官方镜像:
docker pull memgraph/memgraph - 启动容器并开放必要端口:
docker run -p 7687:7687 -p 7444:7444 memgraph/memgraph
容器启动后,你可以通过http://localhost:7444访问Memgraph Lab可视化工具,直接验证服务是否正常运行。
二、Node.js连接Memgraph的最简方式
方案1:使用官方memgraph.js客户端
这是官方维护的适配包,步骤极简:
- 初始化Node.js项目(若未创建):
npm init -y - 安装客户端依赖:
npm install memgraph.js - 编写最简连接测试代码:
const { Memgraph } = require('memgraph.js'); async function testConnection() { const memgraph = new Memgraph(); try { await memgraph.connect(); console.log('✅ 成功连接Memgraph'); // 执行Cypher查询验证 const result = await memgraph.query('CREATE (n:Demo {msg: "Hello Memgraph"}) RETURN n'); console.log('查询结果:', result); } catch (err) { console.error('❌ 连接/查询失败:', err); } finally { await memgraph.disconnect(); } } testConnection();
运行脚本:node index.js,看到成功提示即说明连接正常。
方案2:兼容Neo4j驱动(备选)
Memgraph支持Neo4j Bolt协议,也可以用neo4j-driver快速连接:
- 安装依赖:
npm install neo4j-driver - 测试代码:
const neo4j = require('neo4j-driver'); async function testNeo4jDriver() { const driver = neo4j.driver('bolt://localhost:7687', neo4j.auth.basic('', '')); const session = driver.session(); try { const result = await session.run('CREATE (n:Demo {msg: "Hello via Neo4j Driver"}) RETURN n'); console.log('✅ 连接成功'); console.log('查询结果:', result.records); } catch (err) { console.error('❌ 失败:', err); } finally { await session.close(); await driver.close(); } } testNeo4jDriver();
核心注意事项
- 确保Docker容器处于运行状态,Node.js才能访问7687端口
- 测试环境下Memgraph默认无认证,生产环境需配置用户名密码
- Memgraph Lab(7444端口)可直观查看图数据,方便调试测试
内容的提问来源于stack exchange,提问作者KWriter
相关产品推荐
相关产品推荐

