【发布时间】:2022-11-11 06:55:51
【问题描述】:
我正在学习 nodejs 和 yargs 并尝试使用命令函数在我的代码中实现它。
我正在尝试制作一个基于CLI 的笔记应用程序。
我有两个文件app.js 和utils.js,我运行app.js 和utils.js 在app.js 中导入以使用其中的函数。
有一个我无法调试的问题,当使用remove 选项调用app.js 时,它也会自动调用add 命令,即使它没有被remove 命令显式调用。
输入:
node app.js remove --title="hello"
输出:
{ _: [ 'remove' ], title: 'hello', '$0': 'app.js' }
Already exists!
Operation successful!
这是我的app.js:
// import modules
const validator = require('validator');
const yargs = require('yargs');
// const chalk = require('chalk');
const utils = require('./utils.js');
// version
yargs.version('1.0.0');
const argv = yargs.argv;
console.log(argv);
const command = argv._[0];
// commands
yargs.command({
command: 'add',
describe: 'Add a new note',
builder: {
overwrite: {
describe: 'Overwrite the existing file',
demandOption: true,
type: 'boolean'
},
title: {
describe: 'Title of the note',
demandOption: true,
type: 'string'
},
body: {
body: 'Body of the note',
demandOption: true,
type: 'string'
}
},
handler: utils.addNote(argv.overwrite, argv.title, argv.body)
});
yargs.command({
command: 'remove',
describe: 'Remove a note by its title',
builder: {
title: {
describe: 'Title to search for',
demandOption: true,
type: 'string'
}
},
handler: utils.removeNote(argv.title)
});
// eof
yargs.parse()
这是我的utils.js:
// import
const fs = require('fs');
// load notes
function loadNote() {
try {
const dataBuffer = fs.readFileSync('notes.json');
const stringData = dataBuffer.toString();
const dataJson = JSON.parse(stringData);
return dataJson;
} catch (e) {
return [];
}
}
// add note
function addNote(overwrite, title, body) {
const newNote = {
"title": title,
"body": body
};
const dataJson = loadNote();
if (overwrite) {
fs.writeFileSync('notes.json', JSON.stringify([newNote]));
console.log("Operation successful!");
} else {
let flag = true;
dataJson.forEach(function (object) {
if (object.title === title) {
flag = false;
}
});
if (flag) {
dataJson.push(newNote);
fs.writeFileSync('notes.json', JSON.stringify(dataJson));
console.log("Operation successful!");
} else {
console.log("Already exists!");
}
}
}
// remove notes
function removeNote(title) {
const dataJson = loadNote();
dataJson.filter((object) => object.title !== title);
fs.writeFileSync('notes.json', JSON.stringify(dataJson));
console.log("Operation successful!");
}
// export
module.exports = {
addNote: addNote,
removeNote: removeNote,
};
【问题讨论】:
标签: javascript node.js npm yargs