node.js - 尝试在 node.js 中制作一个简单的命令行习惯跟踪器,在更新和存储数据时遇到问题
问题描述
我是编程新手,在厌倦了处理免费试用和手机上可用的其他应用程序之后,我目前正试图为自己制作一个命令行习惯跟踪器。我想我每天都用我的电脑来学习,我可以在终端中运行一个程序来更新我想要跟踪的一些习惯,而无需使用网页或任何外部的东西。代码如下。
所以,我一直在使用基本的 JS 原则,并且一直在寻找方法来实现在程序执行后提示用户输入的方法。我发现了 readline() 并使用了 Promise 来等待用户输入。一旦用户的输入输入到命令行,我正在使用一个对象来存储我可能想要显示的一些基本信息(开始数据、完成天数、当前连续性)。这当然是一个问题,因为我必须将这些值硬编码到对象中(例如,针对特定习惯的当前连续 27 天)。如果在新的一天,我运行程序并成功地养成了这个习惯,我总是会得到 28 天。该计划没有活力。我意识到我需要某种数据库或不同的方式来动态存储值。
我想我可以使用 JS 的日期功能。正如您在下面的代码中看到的那样,我已经尝试过为习惯的开始日期提供一个值。但是,我想看看除此之外是否有任何设计更好的建议可以让我更容易实施。感谢您的任何和所有建议:)
const { read } = require('fs');
const { exit } = require('process');
const readline = require('readline');
const startDateWater = new Date(2021, 1, 5);
const startDateStretch = new Date(2021, 1, 3);
const startDatePhone = new Date(2021, 1, 22);
const calculateDaysSinceStart = startDate => {
const now = Date.now(); // current date
const difference = now - startDate;
const msPerDay = 24 * 60 * 60 * 1000;
return Math.floor(difference / msPerDay);
};
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const question1 = () => {
return new Promise((resolve, reject) => {
rl.question('Did you drink enough water today? ', answer => {
if (answer.toUpperCase() == 'YES' || answer.toUpperCase() == 'Y') {
console.log('cool');
}
resolve();
});
});
};
const question2 = () => {
return new Promise((resolve, reject) => {
rl.question('Did you stretch today? ', answer => {
if (answer.toUpperCase() == 'YES' || answer.toUpperCase() == 'Y') {
console.log('cool');
}
resolve();
});
});
};
const question3 = () => {
return new Promise((resolve, reject) => {
rl.question('Did you wake up without your phone today? ', answer => {
if (answer.toUpperCase() == 'YES' || answer.toUpperCase() == 'Y') {
console.log('cool');
}
resolve();
});
});
};
const askQuestions = async () => {
await question1();
await question2();
await question3();
rl.close();
};
askQuestions();
解决方案
推荐阅读
- php - URL 中带有百分比的文件名
- javascript - Angular(Javascript)如何使用地图和过滤器为可观察数组过滤日期时间并返回新的相似对象数组
- php - 在网页顶部禁用错误报告
- android - Firebase 云消息服务突然停止接收消息
- ios - EXC_BAD_ACCESS 问题调试
- python - PyQt5 - 使用 QSortFilterProxyModel --> filterAcceptsRow 时退出代码 3
- vba - Excel VBA将所有具有匹配条件的单元格相加
- sql - 如何使用sql server中的外键引用将父表所有id插入子表?更新所有外键值?
- wordpress - 我有多篇文章(帖子)如何让每篇文章都有自己的颜色或单元与单元之间?
- android - 使用矩阵按比例旋转和缩放视图