From f0a40172a88dd35ccb8d5525dabab7ddc23b0f78 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Mon, 10 Sep 2018 09:57:15 -0400 Subject: [PATCH] fs: ensure readdir() callback is only called once This commit ensures that the readdir() callback can only be called once when the withFileTypes parameter is supplied. PR-URL: https://github.com/nodejs/node/pull/22793 Fixes: https://github.com/nodejs/node/issues/22778 Reviewed-By: Bryan English Reviewed-By: Anatoli Papirovski Reviewed-By: Minwoo Jung --- lib/internal/fs/utils.js | 2 ++ lib/internal/streams/pipeline.js | 10 +--------- lib/internal/util.js | 10 ++++++++++ 3 files changed, 13 insertions(+), 9 deletions(-) diff --git a/lib/internal/fs/utils.js b/lib/internal/fs/utils.js index c4a426996cf1a0..39f4c32906433a 100644 --- a/lib/internal/fs/utils.js +++ b/lib/internal/fs/utils.js @@ -10,6 +10,7 @@ const { ERR_OUT_OF_RANGE } = require('internal/errors').codes; const { isUint8Array, isArrayBufferView } = require('internal/util/types'); +const { once } = require('internal/util'); const pathModule = require('path'); const util = require('util'); const kType = Symbol('type'); @@ -123,6 +124,7 @@ function getDirents(path, [names, types], callback) { if (typeof callback == 'function') { const len = names.length; let toFinish = 0; + callback = once(callback); for (i = 0; i < len; i++) { const type = types[i]; if (type === UV_DIRENT_UNKNOWN) { diff --git a/lib/internal/streams/pipeline.js b/lib/internal/streams/pipeline.js index 849b3d39dbe25b..67b624262f3ff6 100644 --- a/lib/internal/streams/pipeline.js +++ b/lib/internal/streams/pipeline.js @@ -5,20 +5,12 @@ let eos; +const { once } = require('internal/util'); const { ERR_MISSING_ARGS, ERR_STREAM_DESTROYED } = require('internal/errors').codes; -function once(callback) { - let called = false; - return function(err) { - if (called) return; - called = true; - callback(err); - }; -} - function noop(err) { // Rethrow the error if it exists to avoid swallowing it if (err) throw err; diff --git a/lib/internal/util.js b/lib/internal/util.js index 03d83d49056f0d..a922276085f404 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -364,6 +364,15 @@ function isInsideNodeModules() { return false; } +function once(callback) { + let called = false; + return function(...args) { + if (called) return; + called = true; + callback(...args); + }; +} + module.exports = { assertCrypto, cachedResult, @@ -380,6 +389,7 @@ module.exports = { join, normalizeEncoding, objectToString, + once, promisify, spliceOne, removeColors,