Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9003

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

$
0
0

TL; DR

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

constperformance=require('perf_hooks').performance;

もしくは

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

詳細

vart0=performance.now();console.log('Do something');vart1=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でもモジュールをインポートせずに使えるようになりそうです。


Viewing all articles
Browse latest Browse all 9003

Trending Articles