3

公式のノード API ドキュメントから Async Hooks のテスト コードを実行しようとしていますがError: Cannot find module 'async_hooks'、コンソールにエラーが表示されます。私はすでにconst async_hooks = require('async_hooks');スクリプトの先頭に含めています。これが私のコードです:

const async_hooks = require('async_hooks');

// Return the ID of the current execution context.
const eid = async_hooks.executionAsyncId();

// Return the ID of the handle responsible for triggering the callback of the
// current execution scope to call.
const tid = async_hooks.triggerAsyncId();

// Create a new AsyncHook instance. All of these callbacks are optional.
const asyncHook =
    async_hooks.createHook({ init, before, after, destroy, promiseResolve });

// Allow callbacks of this AsyncHook instance to call. This is not an implicit
// action after running the constructor, and must be explicitly run to begin
// executing callbacks.
asyncHook.enable();

// Disable listening for new asynchronous events.
asyncHook.disable();

//
// The following are the callbacks that can be passed to createHook().
//

// init is called during object construction. The resource may not have
// completed construction when this callback runs, therefore all fields of the
// resource referenced by "asyncId" may not have been populated.
function init(asyncId, type, triggerAsyncId, resource) { }

// before is called just before the resource's callback is called. It can be
// called 0-N times for handles (e.g. TCPWrap), and will be called exactly 1
// time for requests (e.g. FSReqWrap).
function before(asyncId) { }

// after is called just after the resource's callback has finished.
function after(asyncId) { }

// destroy is called when an AsyncWrap instance is destroyed.
function destroy(asyncId) { }

// promiseResolve is called only for promise resources, when the
// `resolve` function passed to the `Promise` constructor is invoked
// (either directly or through other means of resolving a promise).
function promiseResolve(asyncId) { }

インストールする必要があることに混乱してnpm install async_hooksいますが、それはnodeJsのビルド内モジュールだと思うので、一番上に必要なだけです。

4

1 に答える 1

6

多くの検索を行った後、古いバージョンの nodejs と、Node Version 8.x で最初に導入された async_hooks モジュールを使用していることがわかりました。nvm (ノード バージョン マネージャー) でバージョンをアップグレードした後、問題は解決しました。次のリンクから複数の nodejs バージョンをインストールして管理できます: https://www.digitalocean.com/community/tutorials/how-to-install-node-js-with-nvm-node-version-manager-on-a- vps

nvm が既にインストールされている場合は、次のようにバージョン 8.x に切り替えることができます。

インストールされているすべてのバージョンを一覧表示するには:

 nvm ls

v4.4.4
->       v4.4.7
         v8.8.0
         system
default -> 4.4.7 (-> v4.4.7)
node -> stable (-> v8.8.0) (default)
stable -> 8.8 (-> v8.8.0) (default)

特定のものをオンにするには:

nvm use v8.8.0
Now using node v8.8.0 (npm v5.4.2)
于 2018-08-06T07:01:30.413 に答える