[英]How to save a stdin data in a JSON in Nodejs
我有以下問題,我想在我的控制台中提出一些問題,當我收到答案時,我將它們保存在 json 中然后使用它們,我對 Nodejs 不是很熟悉,我想這很簡單,但它不適合我
嘗試發送customer.Token = answers [1];
發生的事情是我的 json 中不再存在“令牌”。 例如,如果我使用customer.Token =" Hi ";
我的 json 文件更改完美
我需要發送用戶當時給出的答案
我整個早上都在努力完成這項工作,但我找不到解決方案,如果有人知道 <3 這會對我有很大幫助
下面我留下我的代碼
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"}
async
/ await
語法會更易於閱讀和遵循。readline
(Node.js 的內置模塊)可用於獲取用戶的輸入。fs/promises
而不是fs
來利用 Promise。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)
);
readline.close();
}
try {
main();
} catch (e) {
console.error(e);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.