Equivalence of Rails console for Node.js

后端 未结 5 480
梦如初夏
梦如初夏 2021-02-03 18:26

I am trying out Node.js Express framework, and looking for plugin that allows me to interact with my models via console, similar to Rails console. Is there such a thing in NodeJ

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-03 19:03

    Create your own REPL by making a js file (ie: console.js) with the following lines/components:

    1. Require node's built-in repl: var repl = require("repl");
    2. Load in all your key variables like db, any libraries you swear by, etc.
    3. Load the repl by using var replServer = repl.start({});
    4. Attach the repl to your key variables with replServer.context. = . This makes the variable available/usable in the REPL (node console).

    For example: If you have the following line in your node app: var db = require('./models/db') Add the following lines to your console.js

     var db = require('./models/db');
     replServer.context.db = db;
    
    1. Run your console with the command node console.js

    Your console.js file should look something like this:

    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;  
    });
    

    You can even customize your prompt like this:

    var replServer = repl.start({
      prompt: "Node Console > ",
    });
    

    For the full setup and more details, check out: http://derickbailey.com/2014/07/02/build-your-own-app-specific-repl-for-your-nodejs-app/

    For the full list of options you can pass the repl like prompt, color, etc: https://nodejs.org/api/repl.html#repl_repl_start_options

    Thank you to Derick Bailey for this info.


    UPDATE:

    GavinBelson has a great recommendation for running with sequelize ORM (or anything that requires promise handling in the repl).

    I am now running sequelize as well, and for my node console I'm adding the --experimental-repl-await flag.

    It's a lot to type in every time, so I highly suggest adding:

    "console": "node --experimental-repl-await ./console.js"

    to the scripts section in your package.json so you can just run:

    npm run console

    and not have to type the whole thing out.

    Then you can handle promises without getting errors, like this:

    const product = await Product.findOne({ where: { id: 1 });

提交回复
热议问题