diff --git a/lib/internal/util.js b/lib/internal/util.js index 68ff205f80f7c2..dc2d7f1d2ff3f3 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -15,7 +15,8 @@ const { getHiddenValue, setHiddenValue, arrow_message_private_symbol: kArrowMessagePrivateSymbolIndex, - decorated_private_symbol: kDecoratedPrivateSymbolIndex + decorated_private_symbol: kDecoratedPrivateSymbolIndex, + sleep: _sleep } = internalBinding('util'); const { isNativeError } = internalBinding('types'); @@ -374,6 +375,17 @@ function once(callback) { }; } +let validateUint32; + +function sleep(msec) { + // Lazy-load to avoid a circular dependency. + if (validateUint32 === undefined) + ({ validateUint32 } = require('internal/validators')); + + validateUint32(msec, 'msec'); + _sleep(msec); +} + module.exports = { assertCrypto, cachedResult, @@ -391,6 +403,7 @@ module.exports = { normalizeEncoding, once, promisify, + sleep, spliceOne, removeColors, diff --git a/src/node_util.cc b/src/node_util.cc index 9c24985a47a507..4d0b109371fb60 100644 --- a/src/node_util.cc +++ b/src/node_util.cc @@ -161,6 +161,12 @@ static void SetHiddenValue(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(maybe_value.FromJust()); } +static void Sleep(const FunctionCallbackInfo& args) { + CHECK(args[0]->IsUint32()); + uint32_t msec = args[0].As()->Value(); + uv_sleep(msec); +} + void ArrayBufferViewHasBuffer(const FunctionCallbackInfo& args) { CHECK(args[0]->IsArrayBufferView()); args.GetReturnValue().Set(args[0].As()->HasBuffer()); @@ -282,6 +288,7 @@ void Initialize(Local target, env->SetMethodNoSideEffect(target, "getOwnNonIndexProperties", GetOwnNonIndexProperties); env->SetMethodNoSideEffect(target, "getConstructorName", GetConstructorName); + env->SetMethod(target, "sleep", Sleep); env->SetMethod(target, "arrayBufferViewHasBuffer", ArrayBufferViewHasBuffer); Local constants = Object::New(env->isolate()); diff --git a/test/parallel/test-util-sleep.js b/test/parallel/test-util-sleep.js new file mode 100644 index 00000000000000..e4cc62b8e07d64 --- /dev/null +++ b/test/parallel/test-util-sleep.js @@ -0,0 +1,19 @@ +// Flags: --expose-internals +'use strict'; +require('../common'); +const assert = require('assert'); +const { sleep } = require('internal/util'); + +[undefined, null, '', {}, true, false].forEach((value) => { + assert.throws( + () => { sleep(value); }, + /The "msec" argument must be of type number/ + ); +}); + +[-1, 3.14, NaN, 4294967296].forEach((value) => { + assert.throws( + () => { sleep(value); }, + /The value of "msec" is out of range/ + ); +});