Ada*_*NYC 31 console ruby-on-rails rails-console node.js
我正在尝试Node.js Express框架,并寻找允许我通过控制台与我的模型交互的插件,类似于Rails控制台.在NodeJS世界中有这样的事吗?
如果没有,我如何与我的Node.js模型和数据交互,例如手动添加/删除对象,测试数据等方法?
Ira*_*man 50
通过使用以下行/组件创建一个js文件(即:console.js)来创建自己的REPL:
var repl = require("repl");var replServer = repl.start({});replServer.context.<your_variable_names_here> = <your_variable_names_here>.这使得变量在REPL(节点控制台)中可用/可用.例如:如果节点应用程序中有以下行:将以下行
var db = require('./models/db')
添加到console.js
var db = require('./models/db');
replServer.context.db = db;
Run Code Online (Sandbox Code Playgroud)
node console.js您的console.js文件应如下所示:
var repl = require("repl");
var epa = require("epa");
var db = require("db");
// connect to database
db.connect(epa.mongo, function(err){
if (err){ throw err; }
// open the repl session
var replServer = repl.start({});
// attach modules to the repl context
replServer.context.epa = epa;
replServer.context.db = db;
});
Run Code Online (Sandbox Code Playgroud)
您甚至可以像这样自定义提示:
var replServer = repl.start({
prompt: "Node Console > ",
});
Run Code Online (Sandbox Code Playgroud)
有关完整设置和更多详细信息,请访问:http: //derickbailey.com/2014/07/02/build-your-own-app-specific-repl-for-your-nodejs-app/
对于完整的选项列表,您可以传递repl,如提示,颜色等:https://nodejs.org/api/repl.html#repl_repl_start_options
感谢Derick Bailey提供此信息.
这是使用 SQL 数据库执行此操作的方法:
安装并使用Sequelize,它是 Node 对 Rails 中 Active Record 的 ORM 回答。它甚至有一个用于脚手架模型和迁移的 CLI。
node --experimental-repl-await
> models = require('./models');
> User = models.User; //however you load the model in your actual app this may vary
> await User.findAll(); //use await, then any sequelize calls here
Run Code Online (Sandbox Code Playgroud)
TLDR
这使您可以像在 Rails 活动记录中一样访问所有模型。Sequelize 需要一点时间来适应,但在许多方面它实际上比 Active Record 更灵活,同时仍然具有相同的功能。
Sequelize 使用 Promise,因此要在 REPL 中正确运行它们,您将需要在运行 node.js--experimental-repl-await时使用该标志。否则,您可能会收到 bluebird promise 错误
如果您不想输入 require('./models') 步骤,则可以使用 console.js(位于目录根目录下的 REPL 安装文件)来预加载它。但是,我发现在 REPL 中输入这一行更容易
| 归档时间: |
|
| 查看次数: |
8797 次 |
| 最近记录: |