import { execFileSync } from 'node:child_process';
import fs from 'node:fs/promises';
import { existsSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
function resolveNpxCommand(cmdName, startDir, globalBinDirs, opts = {}) {
const { noInstall = false, ignoreExisting = false } = opts;
if (!ignoreExisting) {
let dir = path.resolve(startDir);
while (true) {
const candidate = path.join(dir, 'node_modules', '.bin', `${cmdName}.mjs`);
if (existsSync(candidate)) {
return { source: 'local_node_modules', binPath: candidate, requiresRemoteFetch: false };
}
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
}
for (const gdir of globalBinDirs) {
const candidate = path.join(gdir, `${cmdName}.mjs`);
if (existsSync(candidate)) {
return { source: 'global_path', binPath: candidate, requiresRemoteFetch: false };
}
}
}
if (noInstall) {
return { source: 'missing', errorCode: 'ENOENT_LOCAL_ONLY', requiresRemoteFetch: false };
}
return { source: 'remote_registry', binPath: null, requiresRemoteFetch: true };
}
function parseNpxInvocation(argv) {
const packages = [];
let commandString = null;
let yes = false;
let noInstall = false;
let ignoreExisting = false;
const positional = [];
for (let i = 0; i < argv.length; i++) {
const tok = argv[i];
if (tok === '--yes' || tok === '-y') yes = true;
else if (tok === '--no-install') noInstall = true;
else if (tok === '--ignore-existing') ignoreExisting = true;
else if ((tok === '-p' || tok === '--package') && i + 1 < argv.length) {
packages.push(argv[++i]);
} else if (tok === '-c' && i + 1 < argv.length) {
commandString = argv[++i];
} else {
positional.push(tok);
}
}
let pkgName = null;
let pkgVersion = null;
let cmdArgs = [];
if (positional.length > 0) {
const spec = positional[0];
const atIdx = spec.lastIndexOf('@');
if (atIdx > 0) {
pkgName = spec.slice(0, atIdx);
pkgVersion = spec.slice(atIdx + 1);
} else {
pkgName = spec;
}
cmdArgs = positional.slice(1);
}
return { packages, commandString, yes, noInstall, ignoreExisting, pkgName, pkgVersion, cmdArgs };
}
async function main() {
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'mbsky-npx-'));
const projDir = path.join(tmpDir, 'my-app');
const nestedDir = path.join(projDir, 'src', 'sub');
const localBin = path.join(projDir, 'node_modules', '.bin');
const globalBin = path.join(tmpDir, 'global-bin');
await fs.mkdir(nestedDir, { recursive: true });
await fs.mkdir(localBin, { recursive: true });
await fs.mkdir(globalBin, { recursive: true });
await fs.writeFile(
path.join(localBin, 'demo-cli.mjs'),
[
'const arg = process.argv[2] || "";',
'if (arg === "--version") { console.log("demo-cli@2.1.0"); }',
'else if (arg === "--check-path") { console.log(process.env.PATH.split(process.platform === "win32" ? ";" : ":")[0]); }',
'else { console.log(`< ${arg} >`); }',
].join('\n'),
'utf8',
);
await fs.writeFile(
path.join(globalBin, 'demo-cli.mjs'),
'console.log("demo-cli@1.0.0");\n',
'utf8',
);
const cases = [];
try {
// Case 1: local_bin_resolution_priority
const resolved = resolveNpxCommand('demo-cli', nestedDir, [globalBin]);
const verOut = execFileSync(process.execPath, [resolved.binPath, '--version'], {
encoding: 'utf8',
}).trim();
const actual1 = {
source: resolved.source,
versionOutput: verOut,
requiresRemoteFetch: resolved.requiresRemoteFetch,
};
const expected1 = {
source: 'local_node_modules',
versionOutput: 'demo-cli@2.1.0',
requiresRemoteFetch: false,
};
cases.push({
name: 'local_bin_resolution_priority',
passed: JSON.stringify(actual1) === JSON.stringify(expected1),
expected: expected1,
actual: actual1,
});
// Case 2: no_install_and_ignore_existing_flags
const localStrict = resolveNpxCommand('demo-cli', projDir, [globalBin], { noInstall: true });
const missingStrict = resolveNpxCommand('missing-cli', projDir, [globalBin], { noInstall: true });
const bypassLocal = resolveNpxCommand('demo-cli', projDir, [globalBin], { ignoreExisting: true });
const actual2 = {
localStrictSource: localStrict.source,
missingStrictError: missingStrict.errorCode,
ignoreExistingRemote: bypassLocal.requiresRemoteFetch,
};
const expected2 = {
localStrictSource: 'local_node_modules',
missingStrictError: 'ENOENT_LOCAL_ONLY',
ignoreExistingRemote: true,
};
cases.push({
name: 'no_install_and_ignore_existing_flags',
passed: JSON.stringify(actual2) === JSON.stringify(expected2),
expected: expected2,
actual: actual2,
});
// Case 3: package_spec_and_multi_package_c_parse
const pinned = parseNpxInvocation(['cowsay@1.4.0', 'hello1.4.0']);
const scaffold = parseNpxInvocation(['--yes', 'create-react-app', 'my-app']);
const multi = parseNpxInvocation([
'-p', 'http-server',
'-p', 'browser-sync',
'-c', 'http-server & browser-sync start --proxy "localhost:8080"',
]);
const actual3 = {
pinnedSpec: [pinned.pkgName, pinned.pkgVersion, pinned.cmdArgs[0]],
scaffoldYes: scaffold.yes,
scaffoldPkg: scaffold.pkgName,
multiPackages: multi.packages,
hasCommandString: Boolean(multi.commandString && multi.commandString.includes('browser-sync')),
};
const expected3 = {
pinnedSpec: ['cowsay', '1.4.0', 'hello1.4.0'],
scaffoldYes: true,
scaffoldPkg: 'create-react-app',
multiPackages: ['http-server', 'browser-sync'],
hasCommandString: true,
};
cases.push({
name: 'package_spec_and_multi_package_c_parse',
passed: JSON.stringify(actual3) === JSON.stringify(expected3),
expected: expected3,
actual: actual3,
});
// Case 4: local_cli_execution_and_npm_env_path
const sep = process.platform === 'win32' ? ';' : ':';
const childEnv = { ...process.env, PATH: `${localBin}${sep}${process.env.PATH || ''}` };
const firstPathEntry = execFileSync(
process.execPath,
[path.join(localBin, 'demo-cli.mjs'), '--check-path'],
{ env: childEnv, encoding: 'utf8' },
).trim();
const banner = execFileSync(
process.execPath,
[path.join(localBin, 'demo-cli.mjs'), 'hello-npx'],
{ env: childEnv, encoding: 'utf8' },
).trim();
const actual4 = {
pathPrependedLocalBin: path.resolve(firstPathEntry) === path.resolve(localBin),
banner,
};
const expected4 = {
pathPrependedLocalBin: true,
banner: '< hello-npx >',
};
cases.push({
name: 'local_cli_execution_and_npm_env_path',
passed: JSON.stringify(actual4) === JSON.stringify(expected4),
expected: expected4,
actual: actual4,
});
} finally {
await fs.rm(tmpDir, { recursive: true, force: true });
}
console.log(JSON.stringify({ version: process.version, cases }));
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、Node.js v24.22.3 本地运行环境。
入口文件:projects/nodejs-npx-intro-lab/explore-npx-intro.mjs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-npx-intro.mjs,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a1041.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1063.zip