Cli Todo命令行todo工具使用演示
前言
bald3r-node-todo
是一個用node.js開發(fā)的,主要用于命令行的todo工具,主要使用了fs模塊,目前已經(jīng)發(fā)布至npm
本工具主要使用了面向接口的編程思想,并用jest進行單元測試
鏈接
bald3r-node-todo - npm (npmjs.com)
使用演示
- 首先使用
yarn
或npm
安裝bald3r-node-todo
npm install bald3r-todo yarn global add bald3r-todo
安裝完成后就可以使用全局命令t
來使用了
使用命令行添加一個待辦t add [taskName]
查看當前待辦
二級菜單
清空所有待辦t clear
實現(xiàn)過程
實現(xiàn)命令行參數(shù)
這里我使用了commander庫來實現(xiàn)參數(shù)功能
program .command('add') .description('add a task') .action((...args) => { const words = args.slice(0, -1).join(' ') api.add(words).then(() => { console.log('The task has been successfully added') }, () => { console.log('Failed to add the task') }) }) program .command('clear') .description('clear all tasks') .action(() => { api.clear().then(() => { console.log('All tasks have been successfully removed') }, () => { console.log('Failed to remove all the tasks') }) })
commander默認會有兩個參數(shù),一個是node的路徑,一個是當前文件的路徑,因此我們判斷參數(shù)的數(shù)量是否為2就可以判斷用戶是否傳參
如果用戶沒有傳參,則顯示所有的待辦項
if (process.argv.length === 2) { api.showAll() }
實現(xiàn)可以操作的命令行
這里我使用了inquirer庫來給命令行做了美化,實現(xiàn)可以用方向鍵和回車控制的UI界面
inquirer的使用非常簡單,這里我展示二級菜單作為參考
function askForAction(list, index) { const actions = {markAsUndone, markAsDone, changeTitle, removeTask} inquirer.prompt({ type: 'list', name: 'action', message: 'What to do with the task?', choices: [ {name: 'Exit', value: 'quit'}, {name: 'Mark as Done', value: 'markAsDone'}, {name: 'Mark as Undone', value: 'markAsUndone'}, {name: 'Edit Title', value: 'changeTitle'}, {name: 'Delete', value: 'removeTask'}, ] }).then(answer2 => { const action = actions[answer2.action] action && action(list, index) }) }
這樣便實現(xiàn)了下圖的二級菜單
待辦項保存在本地
使用node.js的fs
模塊來實現(xiàn)對文件的讀寫,這里涉及一個保存路徑的問題,在本項目中,為了方便使用了~
目錄,所有數(shù)據(jù)保存在~/.todo
中
獲取~
目錄:
const homedir = require('os').homedir() const home = process.env.HOME || homedir
考慮到跨平臺使用路徑的表示方式不同,這里使用了node.js中的path
模塊:
const p = require('path') const dbPath = p.join(home, '.todo')
然后使用fs
模塊中的fs.readFile()
和fs.writeFile()
即可完成對數(shù)據(jù)的讀寫。這里需要注意這兩個操作都是異步的,因此用到了Promise
,這里的{flag: 'a+'}
是表示讀取文件,若不存在則創(chuàng)建一個:
read(path = dbPath) { return new Promise((resolve, reject) => { fs.readFile(path, {flag: 'a+'}, (error, data) => { if (error) return reject(error) let list try { list = JSON.parse(data.toString()) } catch (error2) { list = [] } resolve(list) }) }) }
以上就是Cli Todo命令行todo工具使用演示的詳細內(nèi)容,更多關(guān)于Cli Todo命令行todo工具的資料請關(guān)注腳本之家其它相關(guān)文章!