【问题标题】:Getting input from console从控制台获取输入
【发布时间】:2015-11-26 11:14:52
【问题描述】:

我有这个代码

var MongoClient = require('mongodb').MongoClient;

var url = 'mongodb://localhost:27017/clboTest';



// this could have comed from a form from the browser
var objToInsert = {
    _id: 2,
    price: 20000,
    name: stdin,
    description: "20 carat gold ring. ",
    //schoolID: { name: 'RUC', address: 'Roskilde', country: 'Denmark' }
};



MongoClient.connect(url, function (err, db) {

var collection = db.collection('products');

collection.insert(objToInsert, function (err, result) {
    console.log(result);
    db.close();
});

});

我不想硬编码信息(例如价格、名称)。如何在控制台中输入新内容,而不必一遍又一遍地用新信息硬核我的 insert.js 文件?

【问题讨论】:

    标签: javascript node.js input console


    【解决方案1】:

    您可以使用名为 readline-sync 的包。然后你可以在插入对象之前等待用户输入:

    var readlineSync = require('readline-sync');
    
    var name = readlineSync.question('name: ');
    var price = readlineSync.questionInt('price: ');
    
    console.log(name);
    console.log(price);
    
    var objToInsert = {
        _id: 2,
        price: price,
        name: name,
        description: "20 carat gold ring. ",
        //schoolID: { name: 'RUC', address: 'Roskilde', country: 'Denmark' }
    };
    

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      • 1970-01-01
      • 2012-01-08
      • 2015-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多