node.js - 将 yargs 转换为 process.argv
问题描述
我的导师希望我只使用 process.argv 那么我将如何转换它
yargs.command({
command : 'add',
describe: "Adding a Note",
builder: {
title : {
describe: 'Note Title',
demandOption: true,
type : 'string'
},
body: {
describe: 'Note Body',
demandOption: true,
type : 'string'
}
},
handler: function(argv){
notes.addNote(argv.title, argv.body);
}
})
yargs.parse();
进入 process.argv
因为在我的notes.js中我使用的是这段代码
const fs = require('fs');
const addNote = function(title, body){
const notes = loadNotes();
const duplicateNotes = notes.filter(function (note) {
return note.title === title;
});
if(duplicateNotes.length === 0){
notes.push({
title: title,
body: body
})
saveNotes(notes);
console.log('\nNew Note Added Successfully!!!\n');
}
else{
console.log("\nNote Title already existed!!!\n");
}
}
const loadNotes = function() {
try{
const dataBuffer = fs.readFileSync('data.json');
const dataJSON = dataBuffer.toString();
return JSON.parse(dataJSON);
}
catch(e){
return []
}
}
const saveNotes = function(notes) {
const dataJSON = JSON.stringify(notes);
fs.writeFileSync('data.json', dataJSON);
}
module.exports = {
addNote : addNote
}
在终端中我希望能够输入
节点 app.js 读取结果为: 1:我应该买一艘船。2:我应该打个盹。
等等
解决方案
我假设 app.js 文件是您尝试使用 yargs 的地方,并且您已将 notes.js 导入其中。process.argv 将为您提供一个数组,其中前两项是节点路径和您的文件路径,然后是您传递的任何参数。您可以首先切片 process.argv 以删除前 2 个项目,然后假设第一个参数是标题和第二个正文。
const args = process.argv.slice(2);
notes.addNote(args[0], args[1]);
然后你运行 node app.js 'my title' 'my body'
你也可以多玩一点,做一些类似于实际 CLI 接受参数的事情。
假设您实际上希望将 --title 和 --body 作为参数并不管顺序如何都捕获它们。您可以假设 --title 之后的内容将是标题,而 body 之后的内容将是正文。所以你需要做的是在 args 数组中找到 --title ,找到它的索引并加一,然后你就会得到你传递的内容。您还可以将其设为必需并在未定义时返回错误,甚至使用快捷方式。
// We don't need to remove the first two elements since we are looking for
// specific values in the array.
const args = process.argv;
let titleIndex = args.findIndex(element => element === '--title' || element === '-t');
let bodyIndex = args.findIndex(element => element === '--body' || element === '-b');
// If these arguments are not found, it will return -1, so we are always expecting 0 or more.
if (titleIndex < 0) {
console.error('Error: No Title provided');
} else if (bodyIndex < 0) {
console.error('Error: No Body provided');
} else {
const title = args[++titleIndex];
const body = args[++bodyIndex];
notes.addNote(title, body);
}
有了这个你可以运行
node app.js --title 'My Title' --body 'My Body'
node app.js --body 'My Body' --title 'My Title'
node app.js -b 'My Body' -t 'My Title'
推荐阅读
- python - IPython.display.HTML 作为图像
- reactjs - 尝试渲染全局组件时集成测试失败
- f# - 区分联合类型的值的正确名称是什么?
- http - 响应中存在 CORS set-cookie 标头,但未创建 cookie
- r - R: 垂直模式下的针织错误 rticles \vadjust
- java - PDFBox - 提取缩放和旋转的图像
- electron - 我在使用电子生成器打包电子应用程序时遇到问题?
- android - 更改列表项中组件的可见性后,不应用 android listview 的单击事件
- css - 如何使用 css 禁用某些单选按钮
- typescript - Vuetify + typescript 没有重载匹配这个调用错误