Node.jsのネイティブモジュールをフェイクしてみた

Node.jsのネイティブモジュールをフェイクしてみた:

Node.jsで使うことのできるモジュール http fs とかを自分の好きなように置き換えられるようにしてみた.

ちなみに,Node.js自体のバイナリは変更しない.


フェイク被害を受けてもらうプログラム

~/index.js
const http = require('http'); 
http.get('https://example.com/'); 
ここで, http.get() を本来の挙動ではないものにしてしまおう.


require を置き換える

require() で呼ばれる関数はどこ?

自分の用意したモジュールを読み込むようにする.

~/require.js
const overwrapNames = [ 
  'http', 
]; 
 
module.constructor.prototype.require = function (id) { 
  if (typeof id !== 'string') { 
    throw new TypeError(); 
  } 
  if (id === '') { 
    throw new TypeError(); 
  } 
  if (overwrapNames.some(name => name === id)) { 
    return module.constructor._load(`${__dirname}/modules/${id}`, this, false); 
  } 
  return module.constructor._load(id, this, /* isMain */ false); 
}; 
フェイクされて読み込まれるモジュールはこんな感じ.

既にrequireは置き換わっているので,フェイクされたモジュール内で本物のモジュールを使うときは module.constructor._load() を直接呼んで読み込む.

~/modules/http.js
const http = module.constructor._load('http', module, false); 
 
module.exports = { 
  ...http, 
  get(...args) { 
    console.log('DUMMY!', ...args); 
  }, 
}; 


フェイク実行

$ node -r ./require.js ./index.js 
DUMMY! https://example.com/ 

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2024-02-12 22:08:06 RSSフィード2024-02-12 22:00分まとめ(7件)