diff --git a/lib/internal/util.js b/lib/internal/util.js index 1ff25dbc7d2a86..0a319739187fab 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -26,7 +26,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'); @@ -385,6 +386,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, @@ -402,6 +414,7 @@ module.exports = { normalizeEncoding, once, promisify, + sleep, spliceOne, removeColors, diff --git a/src/node_util.cc b/src/node_util.cc index 07a7b69dbd9db4..b9553eaaa6763d 100644 --- a/src/node_util.cc +++ b/src/node_util.cc @@ -169,6 +169,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()); @@ -290,6 +296,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/ + ); +});