js实现cd
JavaScript 实现 CD(Change Directory)功能
在 JavaScript 中模拟命令行中的 cd(Change Directory)功能需要根据运行环境选择不同方法,浏览器端和 Node.js 端的实现方式差异较大。

浏览器环境实现
浏览器端 JavaScript 无法直接访问文件系统,但可以通过虚拟路径或模拟导航实现类似功能:

let currentPath = '/';
function cd(path) {
if (path === '..') {
currentPath = currentPath.split('/').slice(0, -2).join('/') + '/';
} else if (path.startsWith('/')) {
currentPath = path.endsWith('/') ? path : path + '/';
} else {
currentPath += path.endsWith('/') ? path : path + '/';
}
console.log(`Current directory: ${currentPath}`);
}
Node.js 环境实现
Node.js 可以通过 process.chdir() 和 path 模块实现真实的目录切换:
const path = require('path');
const process = require('process');
function cd(targetPath) {
try {
const resolvedPath = path.resolve(process.cwd(), targetPath);
process.chdir(resolvedPath);
console.log(`Current directory: ${process.cwd()}`);
} catch (err) {
console.error(`cd: ${err.message}`);
}
}
增强功能实现
添加路径自动补全和错误处理:
const fs = require('fs');
function enhancedCd(targetPath) {
const currentDir = process.cwd();
const newPath = path.resolve(currentDir, targetPath);
if (!fs.existsSync(newPath)) {
return console.error(`cd: no such directory: ${targetPath}`);
}
const stats = fs.statSync(newPath);
if (!stats.isDirectory()) {
return console.error(`cd: not a directory: ${targetPath}`);
}
process.chdir(newPath);
console.log(`Changed to: ${process.cwd()}`);
}
注意事项
- 浏览器端实现仅为路径字符串模拟,无实际文件系统访问权限
- Node.js 实现需要文件系统权限
- 路径解析时注意处理
.(当前目录)和..(上级目录)特殊字符 - Windows 和 Unix-like 系统的路径分隔符差异需考虑兼容性






