文件模块

2022-01-21  本文已影响0人  kzc爱吃梨

创建 Node.js 命令行项目

安装commander

npm install commander
const program = require('commander');

program
  .option('-x, --xxx', 'what the xxx')
  
program           // 这书子命令
  .command('add')
  .description('add a task')
  .action((...args) => {
    console.log(args.args);
      const words = args.slice(0, -1).join(' ')
    console.log(words);
  });
  
program.parse(process.argv);

console.log(program.xxx)
效果图
效果图

实现创建功能

index.js

const db = require('./db')

module.exports.add = async (title)=> {
    // 读取之前的任务
    const list = await db.read()
    // 往里面添加一个 title 任务
    list.push({title, done: false})
    // 储存任务到文件
    await db.write(list)
}

db.js

const homedir = require('os').homedir()
const home = process.env.HOME || homedir
const p = require('path')
const dbPath = p.join(home, '.todo')
const fs = require('fs')

const db = {
    read(path = dbPath) {
        return new Promise((resolve, reject)=> {
            fs.readFile(path, {flag: 'a+'}, (error, data)=> {  // a+表示没有就创建
                if(error) return reject(error)
                let list 
                try {
                    list = JSON.parse(data.toString())
                } catch(err) {
                    list = []
                }
                resolve(list)
            })
        })
    },
    write(list, path = dbPath) {
        return new Promise((resolve, reject)=> {
            const string = JSON.stringify(list)
            fs.writeFile(path, string + '\n', (error)=> {
                if(error) return reject(error)
                resolve()
            })
        })
    }
}

module.exports = db

完成所有功能

yarn add inquirer

用法:

    inquirer
        .prompt({
            type: 'list',
            name: 'index',              //  类型
            message: '请选你想要的操作的任务?',           // 以下是选项
            choices: [{ name: '退出', value: '-1' }, ...list.map((task, index) => {
                return { name: `${task.done ? '[x]' : '[_]'} ${index + 1} - ${task.title}`, value: index.toString() }
            }), { name: '+ 创建任务', value: '-2' }]
        })
        .then((answers) => {
            // console.log(answers);
            const index = parseInt(answers.index)
            if (index >= 0) {
                // 选择了一个任务
                askForAction(list, index)
            } else if (index === -2) {
                // 创建任务
                askForCreateTask(list)
            }
        });

可输入选项实现

inquirer.prompt({
        type: 'input',
        name: 'title',
        message: "新的标题",
        default: list[index].title,
    }).then((answer) => {
        list[index].title = answer.title
        db.write(list)
    });
实现可选列表

发布到npm

修改package.json

"bin": {
    "t": "cli.js"       // 命令入口文件
  },
  "files": [
    "*.js"  // 上传所有的js文件
  ],
上一篇 下一篇

猜你喜欢

热点阅读