From 21b0792cef0106c5f57d365ba7b66c9250ad550d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Fri, 1 Oct 2021 11:40:23 +0200 Subject: [PATCH] doc: fix typo in ESM example MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs: https://github.com/nodejs/node/pull/37468 PR-URL: https://github.com/nodejs/node/pull/40275 Reviewed-By: Luigi Pinca Reviewed-By: Derek Lewis Reviewed-By: Juan José Arboleda Reviewed-By: Benjamin Gruenbaum Reviewed-By: Zijian Liu Reviewed-By: James M Snell --- doc/api/esm.md | 38 +++++++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/doc/api/esm.md b/doc/api/esm.md index 56691d0622ed3a..44f0d155bc3493 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -960,17 +960,33 @@ export function getFormat(url, context, defaultGetFormat) { return defaultGetFormat(url, context, defaultGetFormat); } -export function transformSource(source, context, defaultTransformSource) { - const { url, format } = context; - - if (extensionsRegex.test(url)) { - return { - source: CoffeeScript.compile(source, { bare: true }) - }; - } - - // Let Node.js handle all other sources. - return defaultTransformSource(source, context, defaultTransformSource); +async function getPackageType(url) { + // `url` is only a file path during the first iteration when passed the + // resolved url from the load() hook + // an actual file path from load() will contain a file extension as it's + // required by the spec + // this simple truthy check for whether `url` contains a file extension will + // work for most projects but does not cover some edge-cases (such as + // extension-less files or a url ending in a trailing space) + const isFilePath = !!extname(url); + // If it is a file path, get the directory it's in + const dir = isFilePath ? + dirname(fileURLToPath(url)) : + url; + // Compose a file path to a package.json in the same directory, + // which may or may not exist + const packagePath = resolvePath(dir, 'package.json'); + // Try to read the possibly nonexistent package.json + const type = await readFile(packagePath, { encoding: 'utf8' }) + .then((filestring) => JSON.parse(filestring).type) + .catch((err) => { + if (err?.code !== 'ENOENT') console.error(err); + }); + // Ff package.json existed and contained a `type` field with a value, voila + if (type) return type; + // Otherwise, (if not at the root) continue checking the next directory up + // If at the root, stop and return false + return dir.length > 1 && getPackageType(resolvePath(dir, '..')); } ```