LoginSignup
2
2

More than 5 years have passed since last update.

既存のモジュールを拡張する

Posted at

Node.jsでオレオレUtilを作成したが、既存のnodeのUtilも使用している。
けれどこんな風には書きたくない。

var util      = require('util');
var util_orig = require('./util'); // なんかいや

そんなとき、以下のように書けば既存のモジュールを拡張しひとまとめにできる。

expand_util.js
var util = require('util');

var isJSON = function(str) {
  try {
    if (!str) {
      return false;
    }

    JSON.parse(str);
    return true;
  } catch (e) {
    return false;
  }
}

if (!('isJSON' in util)) // 既存APIを上書きしない
  util.isJSON = isJSON;

module.exports = util;

こんな風に使える。

var util = require('./expand_util.js');

console.log(util.format("%s", "hogehoe"));           // 既存API
console.log(util.isJSON('{"hogehoge":"fugafuga"}')); // 拡張したAPI

ソースは以下で公開しています。
https://github.com/Peranikov/expand-util

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2