[DAY20] NodeJs 맛보기

Jhey·2024년 11월 8일
0

JavsScript

목록 보기
16/18

0. NodeJs

Node.js란 “V8 Java Script 엔진으로 빌드 된 Java Script 런타임” 이다.

  • 자바스크립트 → 클라이언트용, 웹브라우저용

  • node js → 서버용


1. REPL

node 사용하게 해주는 프롬프트이다. 바로 cmd !!!


2. 인수 넘기기 명령어 활용

2.1 활용1

const args = prosess.argv.slice(2);
console.log(args);

> node app.js test1 test2 test3
> [test1, test2, test3]
  • 인수 test1, test2, test3 을 명령어 뒤에 작성하면 출력할 수 있다.

2.2 활용2

const sum = args.map(Number).reduce()

> node app.js 10 20 30 40 50
> 150
  • 인수를 넘겨서 rsduce를 활용해 누계를 구할 수 있다.

2.3 활용3

const fs = require("fs");
const path = require("path");

const files = process.argv.slice(2, -1); // 찾을 txt 파일
const serachs = process.argv[process.argv.length - 1]; // 찾을 문자

// 정규식을 이용해 조건에 맞는지 확인하기
function extracMatching(content, searchString) {
  const redExp = new RegExp(`([^.]*?${searchString}[^.]*\.)`, "gi");
  return content.match(redExp);
}

function precessFile(files, searchs) {
  let result = "";
  // 받아온 파일에서 조건에 맞는 문장 합치기
  files.forEach((file) => {
    const filePath = path.resolve(file);
    const content = fs.readFileSync(filePath, "utf-8");
    const sentens = extracMatching(content, searchs);

    if (sentens.length > 0) {
      result += `### ${file} ###`;
      result += sentens.join("\n") + "\n\n";
    }
  });
  console.log(result);
}

precessFile(files, serachs);

> node app.js log1.txt log2.txt log3.txt "ERROR -"
  • 인수를 넘겨서 여러개의 파일에서 원하는 조건의 텍스트만 추출할 수있다.

3. 내장객체

global

global.appName = 'My App';

console

console.log('일반 로그');           // 일반 출력
console.error('에러 메시지');        // 에러 출력
console.warn('경고 메시지');         // 경고 출력
console.info('정보 메시지');         // 정보 출력
console.table([{ name: 'Node' }, { name: 'React' }]);  // 객체 표 형태로 출력

require

const os = require('os');  
console.log(os.platform());  
  • require는 다른 모듈이나 파일을 가져올 때 사용한다.

process

  • env
// 환경변수 -> 어디서 실행할지 환경을 선택할때 사용한다.
// 실행할 환경은 NODE_ENV 다.
// NODE_ENV는 통상적 명칭 다른걸로 해도 됨
console.log(process.env.NODE_ENV);
  • env 설정하기

    1. `.env` 파일을 생성한다. 
       NODE_ENV=development
       PORT=3000
       DB_HOST=localhost
       DB_USER=myuser
       DB_PASSWORD=mypassword
    2. env를 사용하려는 파일에서 사용한다.
    // .env 파일에서 환경 변수 로드
    // dotenv는 환경변수를 다룰 때 도움을 주는 라이브러리(외부 모듈)
    require('dotenv').config();
    
    // 환경 변수 사용 예제
    console.log("현재 환경:", process.env.NODE_ENV);
    console.log("서버 포트:", process.env.PORT);
    
  • cwd
console.log(process.cwd());  // 현재 실행 중인 디렉터리 경로
  • platform
console.log(process.platform);  // 'win32', 'darwin', 'linux'
  • exit
if (process.env.NODE_ENV !== 'production') {
  console.error('개발 모드에서는 종료할 수 없습니다.');
  process.exit(1);  
}

4. 내장 모듈

Node.js 제공하는 모듈화되 코드를 의미, 라이브러리, 코드 조각.

OS

const os = require('os');

console.log('플랫폼:', os.platform()); // 'win32', 'linux', 'darwin' 등

Path

const path = require('path');

const filePath = '/user/local/bin/file.txt';

console.log('확장자:', path.extname(filePath)); // '.txt'
console.log('디렉터리명:', path.dirname(filePath)); // '/user/local/bin'
console.log('파일명:', path.basename(filePath)); // 'file.txt'
console.log('절대 경로:', path.resolve('bin', 'file.txt')); // /current/dir/bin/file.txt
console.log('경로 결합:', path.join('/user', 'local', 'bin')); // '/user/local/bin'

URL

const { URL } = require('url');

const myURL = new URL('https://example.com:8000/path?name=John#fragment');

console.log('호스트:', myURL.host); // 'example.com:8000'
console.log('경로명:', myURL.pathname); // '/path'
console.log('쿼리:', myURL.searchParams.get('name')); // 'John'
console.log('프래그먼트:', myURL.hash); // '#fragment'

Crypto

const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
// 암호화 하기
function encrypt(text) {
  const cipher = crypto.createCipheriv(algorithm, key, iv);
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return encrypted;
}
// 복호화 하기
function decrypt(encryptedText) {
  const decipher = crypto.createDecipheriv(algorithm, key, iv);
  let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  return decrypted;
}

const encrypted = encrypt('Hello World');
console.log('암호화된 텍스트:', encrypted);
console.log('복호화된 텍스트:', decrypt(encrypted));
profile
천천히 가더라도 즐겁게 ☁

0개의 댓글

관련 채용 정보