첫 번째 대화형 Node JS CLI 구축
                                            
                                                
                                                
                                                
                                                
                                                
                                                 25476 단어  showdevnodebeginnersjavascript
                    
NodeJS는 CLI라고도 하는 명령줄 인터페이스를 구축할 때 매우 유용할 수 있습니다.
이 게시물에서는 답변을 기반으로 몇 가지 질문을 하고 파일을 생성하는 CLI를 빌드하는 방법을 알려드리겠습니다.
시작하기
완전히 새로운 npm 패키지를 만들어 시작하겠습니다.
mkdir my-script
cd my-script
npm init
NPM은 몇 가지 질문을 할 것입니다. 그런 다음 몇 가지 패키지를 설치해야 합니다.
npm install --save chalk figlet inquirer shelljs
이 패키지의 기능:
분필 - 올바른 터미널 문자열 스타일 지정
figlet - Figlet은 일반 텍스트에서 큰 글자를 만드는 프로그램입니다
inquirer - 일반적인 대화형 명령줄 사용자 인터페이스 모음
shelljs - Node.js용 이식 가능한 Unix 셸 명령
index.js 파일
이제 다음 내용으로
index.js 파일을 생성합니다.#!/usr/bin/env node
const inquirer = require("inquirer");
const chalk = require("chalk");
const figlet = require("figlet");
const shell = require("shelljs");
CLI 계획
코드를 작성하기 전에 CLI가 수행해야 하는 작업을 계획하는 것이 항상 좋습니다.
이 CLI는 한 가지 작업만 수행합니다. 파일을 만듭니다.
몇 가지 질문을 한 후 생성된 파일 경로와 함께 성공 메시지를 표시해야 합니다.
질문은 파일 이름과 확장자가 무엇인지입니다.
// index.js
const run = async () => {
  // show script introduction
  // ask questions
  // create the file
  // show success message
};
run();
첫 번째 기능은 스크립트 소개입니다.
chalk 및 figlet를 사용하여 작업을 완료해 보겠습니다.
const init = () => {
  console.log(
    chalk.green(
      figlet.textSync("Node f*cking JS", {
        font: "Ghost",
        horizontalLayout: "default",
        verticalLayout: "default"
      })
    )
  );
}
const run = async () => {
  // show script introduction
  init();
  // ask questions
  // create the file
  // show success message
};
run();
이제 질문하는 함수를 작성할 차례입니다.
const askQuestions = () => {
  const questions = [
    {
      name: "FILENAME",
      type: "input",
      message: "What is the name of the file without extension?"
    },
    {
      type: "list",
      name: "EXTENSION",
      message: "What is the file extension?",
      choices: [".rb", ".js", ".php", ".css"],
      filter: function(val) {
        return val.split(".")[1];
      }
    }
  ];
  return inquirer.prompt(questions);
};
// ...
const run = async () => {
  // show script introduction
  init();
  // ask questions
  const answers = await askQuestions();
  const { FILENAME, EXTENSION } = answers;
  // create the file
  // show success message
};
inquirer에서 온 상수 FILENAME 및 EXTENSIONS에 주목하십시오.다음 단계는 파일을 만드는 것입니다.
const createFile = (filename, extension) => {
  const filePath = `${process.cwd()}/${filename}.${extension}`
  shell.touch(filePath);
  return filePath;
};
// ...
const run = async () => {
  // show script introduction
  init();
  // ask questions
  const answers = await askQuestions();
  const { FILENAME, EXTENSION } = answers;
  // create the file
  const filePath = createFile(FILENAME, EXTENSION);
  // show success message
};
마지막으로 파일 경로와 함께 성공 메시지를 표시합니다.
const success = (filepath) => {
  console.log(
    chalk.white.bgGreen.bold(`Done! File created at ${filepath}`)
  );
};
// ...
const run = async () => {
  // show script introduction
  init();
  // ask questions
  const answers = await askQuestions();
  const { FILENAME, EXTENSION } = answers;
  // create the file
  const filePath = createFile(FILENAME, EXTENSION);
  // show success message
  success(filePath);
};
node index.js 를 실행하여 스크립트를 테스트해 보겠습니다.
예이! 최종 코드는 다음과 같습니다.
최종 코드
#!/usr/bin/env node
const inquirer = require("inquirer");
const chalk = require("chalk");
const figlet = require("figlet");
const shell = require("shelljs");
const init = () => {
  console.log(
    chalk.green(
      figlet.textSync("Node f*cking JS", {
        font: "Ghost",
        horizontalLayout: "default",
        verticalLayout: "default"
      })
    )
  );
};
const askQuestions = () => {
  const questions = [
    {
      name: "FILENAME",
      type: "input",
      message: "What is the name of the file without extension?"
    },
    {
      type: "list",
      name: "EXTENSION",
      message: "What is the file extension?",
      choices: [".rb", ".js", ".php", ".css"],
      filter: function(val) {
        return val.split(".")[1];
      }
    }
  ];
  return inquirer.prompt(questions);
};
const createFile = (filename, extension) => {
  const filePath = `${process.cwd()}/${filename}.${extension}`
  shell.touch(filePath);
  return filePath;
};
const success = filepath => {
  console.log(
    chalk.white.bgGreen.bold(`Done! File created at ${filepath}`)
  );
};
const run = async () => {
  // show script introduction
  init();
  // ask questions
  const answers = await askQuestions();
  const { FILENAME, EXTENSION } = answers;
  // create the file
  const filePath = createFile(FILENAME, EXTENSION);
  // show success message
  success(filePath);
};
run();
어디에서나 이 스크립트를 실행하려면
package.json 파일에 bin 섹션을 추가하고 npm link를 실행하십시오.{
  "name": "creator",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "chalk": "^2.4.1",
    "figlet": "^1.2.0",
    "inquirer": "^6.0.0",
    "shelljs": "^0.8.2"
  },
  "bin": {
    "creator": "./index.js"
  }
}
$ npm link
$ creator
도움이 되길 바랍니다 :)
Photo by Alex Knight on Unsplash
Reference
이 문제에 관하여(첫 번째 대화형 Node JS CLI 구축), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/hugodias/building-your-first-interactive-node-js-cli-1g2c텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)