一個簡單的nodejs項目(cat-names)分析

來源:互聯網
上載者:User

標籤:

https://github.com/sindresorhus/cat-names

一個非常簡單的nodejs項目,用來方便的擷取貓貓的名字;

安裝

npm install --save cat-names

用法:

const catNames = require(‘cat-names‘);

//擷取隨機貓名

catNames.random();

// => ‘Max‘

 

index.js源碼

非常簡單,不解釋

‘use strict‘;var uniqueRandomArray = require(‘unique-random-array‘);var catNames = require(‘./cat-names.json‘);exports.all = catNames;exports.random = uniqueRandomArray(catNames);

cli.js源碼

#!/usr/bin/env node‘use strict‘;var meow = require(‘meow‘);var catNames = require(‘./‘);var cli = meow([    ‘Examples‘,    ‘  $ cat-names‘,    ‘  Max‘,    ‘‘,    ‘  $ cat-names --all‘,    ‘  Abby‘,    ‘  Angel‘,    ‘  ...‘,    ‘‘,    ‘Options‘,    ‘  --all   Get all names instead of a random name‘]);console.log(cli.flags.all ? catNames.all.join(‘\n‘) : catNames.random());

這裡用到了一個meow模組,這是一個CLI app助手模組。

當我們node cli.js --help 想查看使用方法

(注意當全域安裝後應該cat-names --help)

就會輸出

  Get popular cat names  Examples    $ cat-names    Max    $ cat-names --all    Abby    Angel    ...  Options    --all   Get all names instead of a random name

其中"Get popular cat names"是package.json定義的description。

當我們node cli.js  abc --all 

abc和--all都是參數。

cli就會包含

{  input: [‘abc‘],    flags: {all: true}}

也就是說當

node cli.js --all,因為參數all參數,實際就會調用catNames.all.join(‘\n‘)。而 catNames.all就是讀取cat-names.json,這裡記錄的是所有的貓貓的名字!

一個簡單的nodejs項目(cat-names)分析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.