Skip to content

Commit

Permalink
refactor: use async fs/promises (#1458)
Browse files Browse the repository at this point in the history
  • Loading branch information
dnalborczyk authored May 30, 2022
1 parent 4e29466 commit ae855ef
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 8 deletions.
2 changes: 0 additions & 2 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@ module.exports = {
// require file extensions
'import/extensions': ['error', 'always', { ignorePackages: true }],

'import/no-relative-packages': 'off',

'no-restricted-exports': 'off',
// import buffer explicitly
'no-restricted-globals': [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export default class InProcessRunner {

// lazy load handler with first usage
if (!this.#allowCache) {
clearModule(this.#handlerPath, { cleanup: true })
await clearModule(this.#handlerPath, { cleanup: true })
}

let handler
Expand Down
20 changes: 15 additions & 5 deletions src/lambda/handler-runner/in-process-runner/clearModule.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,36 @@
import { readdirSync } from 'node:fs'
import { readdir } from 'node:fs/promises'
import { createRequire } from 'node:module'
import { dirname, resolve } from 'node:path'

const { keys } = Object

const require = createRequire(import.meta.url)

export default function clearModule(fP, opts) {
export default async function clearModule(fP, opts) {
const options = opts ?? {}
let filePath = fP

if (!require.cache[filePath]) {
const dirName = dirname(filePath)
for (const fn of readdirSync(dirName)) {
const dir = await readdir(dirName)

for (const fn of dir) {
const fullPath = resolve(dirName, fn)
if (
fullPath.substr(0, filePath.length + 1) === `${filePath}.` &&
fullPath.substring(0, filePath.length + 1) === `${filePath}.` &&
require.cache[fullPath]
) {
filePath = fullPath
break
}
}
}

if (require.cache[filePath]) {
// Remove file from parent cache
if (require.cache[filePath].parent) {
let i = require.cache[filePath].parent.children.length

if (i) {
do {
i -= 1
Expand All @@ -35,20 +40,25 @@ export default function clearModule(fP, opts) {
} while (i)
}
}

const cld = require.cache[filePath].children
delete require.cache[filePath]

for (const c of cld) {
// Unload any non node_modules and non-binary children
if (
!c.filename.match(/\/node_modules\//i) &&
!c.filename.match(/\.node$/i)
) {
clearModule(c.id, { ...options, cleanup: false })
// eslint-disable-next-line no-await-in-loop
await clearModule(c.id, { ...options, cleanup: false })
}
}

if (opts.cleanup) {
// Cleanup any node_modules that are orphans
let cleanup = false

do {
cleanup = false
for (const fn of keys(require.cache)) {
Expand Down

0 comments on commit ae855ef

Please sign in to comment.