기본 콘텐츠로 건너뛰기

[Node] Node 관련 패키지들 간략 정리. (갱신 중)

다른 작업을 진행하다가 정말로 오랜만에 다시 Node.js 관련 오픈 소스 분석 작업을 하는데 참조하고 있는 패키지들이 많기도 하다. 아는 것보다는 모르는 것이 더 많아서 뭐가 뭔지 하나도 모르겠다.

앞으로 작업을 하면서 좀 더 다양한 패키지들을 자세하게 알아야 하지만, 당장은 제목과 기능이라도 알아야 이해를 할 수 있을 듯 하다. ㅠㅠ

Packages for NodeJS

bluebird

Full featured promise library with unmatched performance

Examples

  • 설치

    
    npm install bluebird
    
  • 활용법

    
    var Promise = require("bluebird");
    

References


bunyan

Simple and fast JSON Logging Module for node.js services

Examples

  • 설치

    
    $ npm install bunyan
    
  • 활용법

    
    var bunyan = require('bunyan');
    var log = bunyan.createLogger({name: "myapp"});
    log.info("hi");
    

References


camelcase

Convert a dash/dot/underscore/space separated string to camelCase: foo-bar -> fooBar

Examples

  • 설치

    
    $ npm install --save camelcase
    
  • 활용법

    
    const camelCase = require('camelcase');
    

    camelCase(‘foo-bar’); //=> ‘fooBar’ camelCase(‘foo_bar’); //=> ‘fooBar’ camelCase(‘Foo-Bar’); //=> ‘fooBar’ camelCase(’–foo.bar’); //=> ‘fooBar’ camelCase(‘foo__bar’); //=> ‘fooBar’ camelCase(‘foo bar’); //=> ‘fooBar’ camelCase(‘foo’, ‘bar’); //=> ‘fooBar’ camelCase(‘foo’, ‘–bar’); //=> ‘fooBar’

    console.log(process.argv[3]); //=> ‘–foo-bar’ camelCase(process.argv[3]); //=> ‘fooBar’

References


chai

BDD (Behavior-Driven Development) / TDD (Test-Driven Development) Assersion Library for Node

Examples

  • 설치

    
    $ npm install bunyan
    
  • 활용법

    
    // Should
    chai.should();
    

    foo.should.be.a(‘string’); foo.should.equal(‘bar’); foo.should.have.lengthOf(3); tea.should.have.property(‘flavors’).with.lengthOf(3);

    // Expect var expect = chai.expect;

    expect(foo).to.be.a(‘string’); expect(foo).to.equal(‘bar’); expect(foo).to.have.lengthOf(3); expect(tea).to.have.property(‘flavors’).with.lengthOf(3);

    // Assert var assert = chai.assert;

    assert.typeOf(foo, ‘string’); assert.equal(foo, ‘bar’); assert.lengthOf(foo, 3) assert.property(tea, ‘flavors’); assert.lengthOf(tea.flavors, 3);

References


chalk

Terminal String Styling done right

Examples

  • 설치

    
    $ npm install chalk
    
  • 활용법

    
    const chalk = require('chalk');
    console.log(chalk.blue('Hello world!'));
    

References


chokidar

A neat wrapper around node.js fs.watch / fs.watchFile / fsevents.

Examples

  • 설치

    
    $ npm install chokidar --save
    
  • 활용법

    
    var chokidar = require('chokidar');
    

    // One-liner for current directory, ignores .dotfiles chokidar.watch(’.’, {ignored: /(^|[/\])…/}).on(‘all’, (event, path) => { console.log(event, path); }); // Example of a more typical implementation structure:

    // Initialize watcher. var watcher = chokidar.watch(‘file, dir, glob, or array’, { ignored: /(^|[/\])…/, persistent: true });

    // Something to use when events are received. var log = console.log.bind(console); // Add event listeners. watcher .on(‘add’, path => log(File ${path} has been added)) .on(‘change’, path => log(File ${path} has been changed)) .on(‘unlink’, path => log(File ${path} has been removed));

    // More possible events. watcher .on(‘addDir’, path => log(Directory ${path} has been added)) .on(‘unlinkDir’, path => log(Directory ${path} has been removed)) .on(‘error’, error => log(Watcher error: ${error})) .on(‘ready’, () => log(‘Initial scan complete. Ready for changes’)) .on(‘raw’, (event, path, details) => { log(‘Raw event info:’, event, path, details); });

    // ‘add’, ‘addDir’ and ‘change’ events also receive stat() results as second // argument when available: http://nodejs.org/api/fs.html#fs_class_fs_stats watcher.on(‘change’, (path, stats) => { if (stats) console.log(File ${path} changed size to ${stats.size}); });

    // Watch new files. watcher.add(‘new-file’); watcher.add([‘new-file-2’, ‘new-file-3’, ‘**/other-file*’]);

    // Get list of actual paths being watched on the filesystem var watchedPaths = watcher.getWatched();

    // Un-watch some files. watcher.unwatch(‘new-file*’);

    // Stop watching. watcher.close();

    // Full list of options. See below for descriptions. (do not use this example) chokidar.watch(‘file’, { persistent: true,

    ignored: ‘*.txt’, ignoreInitial: false, followSymlinks: true, cwd: ‘.’,

    usePolling: true, interval: 100, binaryInterval: 300, alwaysStat: false, depth: 99, awaitWriteFinish: { stabilityThreshold: 2000, pollInterval: 100 },

    ignorePermissionErrors: false, atomic: true // or a custom ‘atomicity delay’, in milliseconds (default 100) });

References


escape-string-regexp

Escape RegExp Special Characters

Examples

  • 설치

    
    $ npm install --save escape-string-regexp
    
  • 활용법

    
    const escapeStringRegexp = require('escape-string-regexp');
    

    const escapedString = escapeStringRegexp(‘how much $ for a unicorn?’); //=> ‘how much $ for a unicorn?’

    new RegExp(escapedString);

References


eslint

Pluggable Linting utility for JavaScript and JSX

Examples

  • 설치

    
    $ npm install eslint
    
  • 활용법

    
    Rule 정의 파일 구성
    $ npm run eslint .
    

References


graceful-fs

drop-in replacement for the fs module, making various improvements.

Examples

  • 설치

    
    $ npm install graceful-fs
    
  • 활용법

    
    // use just like fs
    var fs = require('graceful-fs')
    

    // now go and do stuff with it… fs.readFileSync(‘some-file-or-whatever’)

    // // Global Patching //

    // Make sure to read the caveat below. var realFs = require(‘fs’) var gracefulFs = require(‘graceful-fs’) gracefulFs.gracefulify(realFs)

References


istanbul

JS Code Coverage tool written in JS

Examples

  • 설치

    
    $ npm install -g istanbul
    
  • 활용법

    
    $ istanbul cover test.js
    

References


jscs

Javascript Code Style Checker

Examples

  • 설치

    
    $ npm install jscs  
    

  • 활용법

    
    $ jscs file.js --preset=airbnb
    

References


minimist

guts of optimist's argument parser without all the fanciful decoration

Examples

  • 설치

    
    $ npm install minimist
    
  • 활용법

    
    var argv = require('minimist')(process.argv.slice(2));
    console.dir(argv);
    

References


mocha

Fun, Simple, Flexible Javascript Test Framework

Examples

  • 설치

    
    $ npm install mocha
    
  • 활용법

    
    Assert 파일 작성
    $ mocha test/index.js
    

References


nyc

Istanbul command line interface

Examples

  • 설치

    
    $ npm i nyc --save-dev
    
  • 활용법

    • package.json script 설정

      
      {
        "script": {
          "test": "nyc tap ./test/*.js"
        }
      }
      
    • 실행

      
      $ nyc npm test
      $ nyc --reporter=lcov --reporter=text-lcov npm test
      

References


require-dir

Node.js 지원을 위해 지정한 디렉터리 단위로 존재하는 파일들을 일괄 require() 처리

Examples

  • 설치

    
    $ npm install require-dir
    
  • 활용법

    
    var requireDir = require('require-dir');
    var dir = requireDir('./path/to/dir');
    var dir = requireDir('./path/to/dir', {recurse: true});
    

References


rewire

Easy monkey-patching for node.js unit tests

Examples

  • 설치

    
    $ npm install rewire
    
  • 활용법

    
    자세한 활용법은 아래 사이트 설명 참조
    

References


shelljs, shelljs/shx

shelljs: Portable Unix shell commands for Node.js
shelljs/shx: Portable Shell Commands for Node.js

Examples

  • 설치

    
    $ npm install shelljs
    $ npm install shelljs/shx   # for command line
    
  • 활용법 (shelljs)

    
    var shell = require('shelljs');
    

    if (!shell.which(‘git’)) { shell.echo(‘Sorry, this script requires git’); shell.exit(1); }

    // Copy files to release dir shell.rm(’-rf’, ‘out/Release’); shell.cp(’-R’, ‘stuff/’, ‘out/Release’);

    // Replace macros in each .js file shell.cd(‘lib’); shell.ls(’*.js’).forEach(function (file) { shell.sed(’-i’, ‘BUILD_VERSION’, ‘v0.1.2’, file); shell.sed(’-i’, /^.REMOVE_THIS_LINE.$/, ‘’, file); shell.sed(’-i’, /.REPLACE_LINE_WITH_MACRO.\n/, shell.cat(‘macro.js’), file); }); shell.cd(’…’);

    // Run external tool synchronously if (shell.exec(‘git commit -am “Auto-commit”’).code !== 0) { shell.echo(‘Error: Git commit failed’); shell.exit(1); }

  • 활용법 (shelljs/shx)

    
    # used in command line using shx
    $ shx mkdir -p foo
    $ shx touch foo/bar.txt
    $ shx rm -rf foo
    

References


sinon

Standalone test spies, stubs and mocks for Javascript. work with any unit testing framework.

Examples

  • 설치

    
    $ npm install sinon
    
  • 활용법

    
    자세한 활용법은 아래 사이트 설명 참조
    

References


standard

Javascript 표준 스타일 가이드 with Linter & Automatic code fixer

Examples

  • 설치

    
    $ npm install standard --save-dev
    
  • 활용법

    
    $ standard
    Error: Use JavaScript Standard Style
      lib/torrent.js:950:11: Expected '===' and instead saw '=='.
    $ standard "src/util/**/*.js" "test/**/*.js"
    

References


tildify

Convert an absolute path to the tilde path: /Users/sindresorhus/dev to ~/dev

Examples

  • 설치

    
    $ npm install --save tildify
    
  • 활용법

    
    const tildify = require('tildify');
    

    tildify(’/Users/sindresorhus/dev’); //=> ‘~/dev’

References


yargs

Yargs helps you build interactive command line tools by parsing arguments and generating an elegant user interface

Examples

  • 설치

    
    $ npm install yargs
    
  • 활용법

    
    #!/usr/bin/env node
    

    require(‘yargs’) .usage(’$0 [args]’) .command(‘hello [name]’, ‘welcome ter yargs!’, { name: { default: ‘default name’ } }, function (argv) { console.log(‘hello’, argv.name, ‘welcome to yargs!’) }) .help() .argv

    자세한 활용법은 아래 사이트 설명 참조

References



Written by Morris (ccambo@gmail.com - MSFL)


댓글

이 블로그의 인기 게시물

OData 에 대해서 알아보자.

얼마 전에 어떤 회사에 인터뷰를 하러 간 적이 있었다. 당시 그 회사는 자체 솔루션을 개발할 기술인력을 찾고 있었고 내부적으로 OData를 사용한다고 했다. 좀 창피한 이야기일 수도 있지만 나름 기술적인 부분에서는 많은 정보를 가지고 있다고 했던 것이 무색하게 OData란 단어를 그 회사 사장님에게서 처음 들었다. 작고, 단순한 사이트들만을 계속해서 작업을 하다 보니 어느덧 큰 줄기들을 잃어버린 것을 느끼기 시작했다. 명색이 개발이 좋고, 기술적인 기반을 만들려고 하는 인간이 단어조차도 모른다는 것은 있을 수 없는 것이라서 다시 새로운 단어들과 개념들을 알아보는 시간을 가지려고 한다. OData (Open Data Protocol) 란? 간단히 정리하면 웹 상에서 손쉽게 데이터를 조회하거나 수정할 수 있도록 주고 받는 웹(프로토콜)을 말한다. 서비스 제공자 입장에서는 웹으로 데이터를 제공하는 방식으로 각 포탈 사이트들이 제공하는 OPEN API 포맷을 독자적인 형식이 아니라 오픈된 공통규약으로 제공 가능하며, 개발자는 이 정보를 다양한 언어의 클라이언트 라이브러리로 어플리케이션에서 소비할 수 있도록 사용하면 된다. 공식 사이트는 www.odata.org 이며 많은 언어들을 지원하고 있다. 좀더 상세하게 정의를 해 보면 OData는 Atom Publishing Protocol  (RFC4287) 의 확장 형식이고 REST (REpresentational State Transfer) Protocol 이다. 따라서 웹 브라우저에서 OData 서비스로 노출된 데이터를 볼 수 있다. 그리고 AtomPub 의 확장이라고 했듯이 데이터의 조회만으로 한정되는 것이 아니라 CRUD 작업이 모두 가능하다. Example 웹 브라우저에서 http://services.odata.org/website/odata.svc 를 열어 보도록 하자. This XML file does not appear to have any style in...

C# 에서 Timer 사용할 때 주의할 점.

예전에 알고 지내시던 분의 질문을 받았다. Windows Forms 개발을 하는데, 주기적 (대략 1분)으로 데이터 요청을 하는 프로그램을 작성하기 위해서 Timer 를 사용하는데, 어떤 기능을 처리해야 하기 때문에 Sleep 을 같이 사용했다고 한다. 여기서 발생하는 문제는 Sleep 5초를 주었더니, Timer 까지 5초 동안 멈춘다는 것이다. Timer 라는 것은 기본적으로 시간의 흐름을 측정하는 기능이기 때문에 Sleep 을 했다고 해서 Timer 가 멈추는 일은 생겨서는 안된다. 그러나 실제 샘플을 만들어 보면 ... Timer 가 Sleep 만큼 동작이 멈추는 것을 확인할 수 있다. Windows Forms 는 UI Thread 를 사용하는 것으로 최적화 되어 있으며 여기서 Timer 를 쓰면 UI Thread 에 최적화된 System.Windows.Forms.Timer 가 사용된다. 여기서 문제의 발생이 시작되는 것이다. Sleep 을 사용하게 되면 UI Thread 가 Sleep 이 걸리기 때문에 여기에 속한 Timer 까지도 멈추는 것이다. 이런 문제를 해결하기 위해서는 System.Threading.Timer 를 사용해야 한다. 이 Timer 는 별도의 Thread 에서 동작하기 때문에 Sleep 의 영향을 받지 않는다. 언뜻 보면 쉬운 해결 방법인 것 같지만 Thread 가 분리되었기 때문에 Timer 가 돌아가는 Thread 에서 UI Thread 의 메서드나 컨트롤에 접근하기 위해서는 별도의 명령을 사용해야 하는 문제가 존재한다. 자~ 그럼 여기서 Timer 에 대해서 다시 한번 정리해 보도록 하자. .NET 에서 제공하는 Timer 들 .NET 에서는 기본적으로 3가지 Timer를 제공하고 있다. (MSDN) System.Windows.Forms.Timer - 사용자가 지정한 간격마다 이벤트를 발생시키며 Windows Forms 응용 프로그램에서 사용할 수 있도록 최적화 되어 있다. System...

[Logging] NLog 사용법 정리...

SCSF 에는 기본적으로 Enterprise Library가 사용된다. 예전에도 그랬지만 기능은 훌륭하고 많은 부분에서 최적화(?)된 것일지도 모르지만, 역시나 사용하기에는 뭔가 모르게 무겁고, 사용하지 않는 기능이 더 많다라는 느낌을 지울수가 없다. 이번 프로젝트도 SCSF를 기반으로 하고 있지만, Enterprise Library를 걷어내고 각 부분에 전문화된 오픈 소스를 사용하기로 하였다. 예전에는 Log4Net을 사용했지만, 대량 사용자 환경에서는 메모리 누수와 기타 문제점이 존재한다는 MS 컨설턴트(?)의 전해진 말을 들은 후로는 사용하지 않는다. 대안으로 사용하는 것이 NLog 이다. 조금 후에는 3.0 버전도 나온다고 홈 페이지에 기재되어 있지만, 그 때가 되면 프로젝트는 끝나기 때문에 현재 2.1.0 버전을 사용하기로 했다. [원본 출처] http://cloverink.net/most-useful-nlog-configurations-closed/ 위의 참조 자료에는 다양한 정보들이 존재하므로 꼭 링크를 통해서 관련된 정보를 확인하고 이해하는 것이 좋을 듯 하다. 여기서는 당장 필요한 부분만을 정리하도록 한다. [ Logger 찾기 ] 기본적으로 Logger가 존재하는 클래스를 기반으로 Logger 정보를 구성한다. Logger logger = LogManager.GetCurrentClassLogger(); 주로 Namespace 기반으로 Logger를 설정하는 경우에 유연하게 사용할 수 있다. 또 다른 방법으로는 지정한 문자열로 특정 Logger를 직접 선택하는 방법도 제공된다. 이를 혼용해서 Namespace와 직접 지정 방식을 같이 사용할 수도 있다. 물론 Logger 환경 설정에서 Wildcard (*)를 지정할 수도 있다. Logger logger = LogManager.GetLogger("Database.Connect"); Logger logger = LogManager.Get...