LoginSignup
11
6

More than 3 years have passed since last update.

Node.jsでperformance.now()を使用した際に"ReferenceError: performance is not defined"というエラーが出る

Posted at

TL; DR

以下のいずれかの方法でperformanceオブジェクトを宣言する。

const performance = require('perf_hooks').performance;

もしくは


const { performance } = require('perf_hooks');

詳細

var t0 = performance.now();
console.log( 'Do something' );
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");

上記のようなコードをNode.jsで実行するとReferenceError: performance is not definedというエラーが出た。
Node.jsでPerformance APIを使用するにはPerformance Timing APIのドキュメントにあるようにpref_hookモジュールをインポートしてあげる必要があるみたいでした。

発展

Chromeでは、わざわざインポートしなくてもperformance.now()が使えるのにどうしてNode.jsではインポートする必要があるのか疑問に思いとさらに調べてみました。

どうやらNode.jsではPerformance APIはまだ試験的に実装されている段階なのでChromeとは違いglobalオブジェクト(Chromeの場合はwindow)にエクスポーズしていないみたいでした1
globalにエクスポーズするプルリクも既に出ている2ので試験的な段階が終了すればNode.jsでもモジュールをインポートせずに使えるようになりそうです。

11
6
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
11
6