【问题标题】:How to save a stdin data in a JSON in Nodejs如何在 Nodejs 中以 JSON 格式保存标准输入数据
【发布时间】:2021-03-19 18:56:39
【问题描述】:

我有以下问题,我想在我的控制台中问一些问题,当我收到答案时我将它们保存在一个 json 中然后使用它们,我对 Nodejs 不是很熟悉,我想它是什么简单但对我不起作用

当尝试发送 customer.Token = answers [1]; 时,我的 json 中不再存在“令牌”。例如,如果我使用customer.Token =" Hi ";,我的 json 文件会完美更改

我需要发送用户当时给出的答案

我整个上午都在努力完成这项工作,但我找不到解决方案,如果有人知道

下面我留下我的代码

   const customer = require('./db.json');

const fs = require("fs");

function jsonReader(filePath, cb) {
  fs.readFile(filePath, (err, fileData) => {
    if (err) {
      return cb && cb(err);
    }
    try {
      const object = JSON.parse(fileData);
      return cb && cb(null, object);
    } catch (err) {
      return cb && cb(err);
    }
  });
}

jsonReader("./db.json", (err, customer) => {
    if (err) {
      console.log("Error reading file:", err);
      return;
    }

    customer.Token = "HI";
    
    fs.writeFile("./db.json", JSON.stringify(customer), err => {
      if (err) console.log("Error writing file:", err);
    });
  });


var questions = ['Cual es tu nombre?' ,
                 'Cual es tu Token?'  ,
                 'Cual es tu numero de orden?'
                ]

var answers = [];

function question(i){
    process.stdout.write(questions[i]);
}

process.stdin.on('data', function(data){
    answers.push(data.toString().trim());

    if(answers.length < questions.length){
        question(answers.length);
    }else{
        process.exit();
    }
    
})

question(0);

y en mi JSON:

{"name":"Jabibi","order_count":103,"Token":"HI"}

【问题讨论】:

    标签: javascript node.js json stdout stdin


    【解决方案1】:
    • 虽然可以让您的脚本与传统回调一起使用,但我认为切换到 Promise 和现代 async/await 语法会更易于阅读和遵循。
    • readline(Node.js 的内置模块)可用于获取用户的输入。
    • 您可以使用 fs/promises 而不是 fs 来利用 Promise。
    • 您似乎正在尝试创建一个新的客户对象(使用用户的输入),然后将其作为 JSON 写入您的文件系统。
    • 下面的脚本写入临时文件路径。一旦测试正确的数据被正确写入文件,您就可以更改文件路径(我不想覆盖您机器上的现有文件)。

    const fs = require("fs/promises");
    
    const readline = require("readline").createInterface({
      input: process.stdin,
      output: process.stdout,
    });
    
    function getUserInput(displayText) {
      return new Promise((resolve) => {
        readline.question(displayText, resolve);
      });
    }
    
    const questions = [
      ["name", "Cual es tu nombre?"],
      ["token", "Cual es tu Token?"],
      ["order_count", "Cual es tu numero de orden?"],
    ];
    
    async function main() {
      const newCustomer = {};
    
      for (const [property, question] of questions) {
        const answer = await getUserInput(question.concat("\n"));
        newCustomer[property] = answer;
      }
    
      console.log("New customer:", newCustomer);
    
      const oldCustomer = await fs
        .readFile("./db.json")
        .then((data) => data.toString("utf-8"))
        .then(JSON.parse);
    
      // You can do something with old customer here, if you need to.
      console.log("Old customer:", oldCustomer);
    
      // I don't want to overwrite any existing file on your machine.
      // You can change the file path and data below to whatever they should be
      // once you've got your script working.
      await fs.writeFile(
        `./db_temp_${Date.now()}.json`,
        JSON.stringify(newCustomer)
      );
    
    }
    
    main()
      .catch(console.error)
      .finally(() => readline.close());
    

    【讨论】:

    • 非常感谢!它似乎完美无缺!我将研究它以很好地理解它并继续在我的项目中应用它
    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    相关资源
    最近更新 更多