How to use the cd function from shelljs

Find comprehensive JavaScript shelljs.cd code examples handpicked from public code repositorys.

shelljs.cd is a JavaScript API that allows you to change the current working directory of a Node.js process using the shell command cd.

50
51
52
53
54
55
56
57
58
59
  cleanInit()

  await cloneFiles()

  shell.echo('\nCleaning files.')
  shell.cd(path.resolve(__dirname))
  shell.rm('-rf', cacheDir)

  shell.echo('\ndone.')
}
fork icon669
star icon0
watch icon88

114
115
116
117
118
119
120
121
122
123

sh.cd(extensionDir);

extensionList.forEach(extension => {
  if (sh.test('-d', extension.path)) {
    sh.cd(extension.path);
    sh.exec('git checkout ' + extensionBranch);
    sh.exec('git pull');
  } else {
    sh.exec('git clone -b ' + extensionBranch + ' ' + extension.url);
fork icon369
star icon0
watch icon92

+ 5 other calls in file

How does shelljs.cd work?

shelljs.cd is a JavaScript API that allows you to change the current working directory of a Node.js process using the shell command cd. When you call shelljs.cd with a directory path as its argument, it will change the current working directory of the Node.js process to the specified directory. If the directory path is relative, it will be interpreted as relative to the current working directory of the Node.js process. If the directory path is absolute, it will be used as-is. Here's an example of how you could use shelljs.cd to change the current working directory of a Node.js process: javascript Copy code {{{{{{{ const shell = require('shelljs'); console.log(`Current working directory: ${process.cwd()}`); shell.cd('../'); console.log(`New working directory: ${process.cwd()}`); In this example, we first log the current working directory of the Node.js process using the process.cwd() method. We then call shelljs.cd with a relative directory path to move up one directory level. Finally, we log the new current working directory of the Node.js process to the console using process.cwd() again. By using shelljs.cd, we can easily change the current working directory of a Node.js process within our JavaScript code, making it easy to work with files and directories in different locations.

31
32
33
34
35
36
37
38
39
40
// fs.writeFileSync(path.join(process.cwd(), './.docsite'), '');

fs.copySync(path.join(__dirname, '../website'), dir);
console.log(chalk.green('Project folder was created successfully.'));

shell.cd(dir);
try {
  shell.exec('npm i');
} catch (err) {
  console.log(chalk.red('Dependencies install failed, please reinstall again!'));
fork icon236
star icon0
watch icon46

198
199
200
201
202
203
204
205
206
const targetPath = path.join(STATIC_URL, `bklesscode-proj-${projectId}`)
const projectPath = path.resolve('./')

return new Promise(async (resolve, reject) => {
    try {
        shell.cd(STATIC_URL)
        const targz = `tar zcf bklesscode-proj-${projectId}.tar.gz -C ./${sourceDir} .`
        shell.exec(targz)
        shell.cd(projectPath)
fork icon32
star icon31
watch icon9

+ 3 other calls in file

Ai Example

1
2
3
4
5
6
7
const shell = require("shelljs");

console.log(`Current working directory: ${process.cwd()}`);

shell.cd("../");

console.log(`New working directory: ${process.cwd()}`);

In this example, we first log the current working directory of the Node.js process using the process.cwd() method. We then call shelljs.cd with a relative directory path to move up one directory level. Finally, we log the new current working directory of the Node.js process to the console using process.cwd() again. By using shelljs.cd, we can easily change the current working directory of a Node.js process within our JavaScript code, making it easy to work with files and directories in different locations.

96
97
98
99
100
101
102
103
104
105
if (!pkgJson.dependencies) pkgJson['dependencies'] = {};
pkgJson.dependencies.snarkyjs = '0.*';
fs.writeJSONSync(path.join('ui', 'package.json'), pkgJson, { spaces: 2 });

// Use `install`, not `ci`, b/c these won't have package-lock.json yet.
sh.cd('ui');
await step(
  'UI: NPM install',
  `npm install --silent > ${isWindows ? 'NUL' : '"/dev/null" 2>&1'}`
);
fork icon29
star icon93
watch icon20

+ 104 other calls in file

26
27
28
29
30
31
32
33
34
35
var commitMessage = shelljs.exec('git log -1 --pretty=%B').stdout.trim();
console.log('COMMIT MESSAGE: ' + commitMessage);
// create clone directory
fs.mkdirSync('./ej2aspmvc');
// navigate to clone location
shelljs.cd('./ej2aspmvc');
var appPath = process.env.BRANCH_NAME == 'master' ? 'ej2aspmvc' : 'ej2aspnetmvc';
// get git url for pull the repository
var remotePath = 'https://' + process.env.EJ2_AZURE_CRED + '@' + appPath + '.scm.azurewebsites.net:443/' + appPath + '.git';
shelljs.exec('git init && git fetch ' + remotePath + ' master && git checkout master');
fork icon27
star icon9
watch icon13

+ 99 other calls in file

49
50
51
52
53
54
55
56
57
58
59
60
61


  return arrayOfFiles;
};


async function main() {
  shell.cd(projectRoot);


  if (!shell.which('anchor')) {
    shell.echo(
      "Sorry, this script requires 'anchor' to be installed in your $PATH"
fork icon24
star icon26
watch icon5

+ 15 other calls in file

199
200
201
202
203
204
205
206
207
208
} else {
  certInfo = "US;NY;SomeOrg;SomeName";
  fs.writeFileSync(`./.certinfo`, certInfo);
}
certInfo = certInfo.split(";");
shell.cd(`..`);
console.log("");
console.log(
  `${utils.osPrefix}ZXPSignCmd -selfSignedCert ${certInfo[0]} ${certInfo[1]} ${certInfo[2]} ${certInfo[3]} ${password} ./${rootpath}/archive/temp1.p12`
);
fork icon4
star icon4
watch icon0

216
217
218
219
220
221
222
223
224
225
// need to avoid the pod install step - we'll do it later
exec(
  `node ${reactNativePackagePath}/cli.js init RNTestProject --template ${localNodeTGZPath} --skip-install`,
);

cd('RNTestProject');
exec('yarn install');

// need to do this here so that Android will be properly setup either way
exec(
fork icon2
star icon0
watch icon0

+ 5 other calls in file

64
65
66
67
68
69
70
71
72
73

const cdRegexp = /^(?:cd\s)([\S|/|.|.]+)+$/i;
const cdResult = cmd.match(cdRegexp);

if (cdResult) {
  shell.cd(path.join(shell.pwd().stdout, cdResult[1]));
  return true;
}

const exitCode = shell.exec(utils.normalizeCommandWithNvm(cmd), {silent: this._silent}).code;
fork icon1
star icon4
watch icon162

+ 9 other calls in file

111
112
113
114
115
116
117
118
119
120

log.debug("Testing artifacts");
await exec(`${shellDir}/common/initialize-dependencies-java.sh ${taskParams["languageVersion"]}`);  
if (testTypes.includes(TestType.Static)) {
  log.debug("Commencing static tests");
  shell.cd(workdir);
  await exec(`${shellDir}/test/static-java.sh \
  ${taskParams["buildTool"]} \
  ${version} \
  ${taskParams["sonarUrl"]} \
fork icon1
star icon0
watch icon6

+ 161 other calls in file

54
55
56
57
58
59
60
61
62
63
64
 * Changes the directory
 * @param {String} dir
 * @returns {Void}
 */
function cd(dir) {
    Shell.cd(dir);
}


/**
 * Changes the directory, if required
fork icon0
star icon3
watch icon0

+ 3 other calls in file

118
119
120
121
122
123
124
125
126
127
    }
}

compile_code(output) {
    return new Promise((resolve, reject) => {
        shell.cd(path.join(__dirname, '..'));
        if (!fs.existsSync((path.join(__dirname, '..', 'skeleton')))) {
            shell.exec('git clone --recursive https://github.com/hardwario/twr-skeleton.git skeleton', (error, stdout, stderr) => {
                if (error) {
                    console.warn(error);
fork icon0
star icon2
watch icon1

+ 45 other calls in file

118
119
120
121
122
123
124
125
126
127
    }
}

compile_code(output) {
    return new Promise((resolve, reject) => {
        shell.cd(path.join(this.user_folder));
        if (!fs.existsSync((path.join(this.user_folder, 'skeleton')))) {
            shell.exec('git clone --recursive https://github.com/hardwario/twr-skeleton.git skeleton', (error, stdout, stderr) => {
                if (error) {
                    console.warn(error);
fork icon0
star icon2
watch icon1

+ 50 other calls in file

1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
},

// ============================================================================
goTo: (p) => {
    Util.logCyan(`go to: ${p}`);
    const sh = shelljs.cd(p);
    if (sh.code) {
        Util.logRed(sh.stderr);
    }
    return sh.code;
fork icon0
star icon1
watch icon1

+ 7 other calls in file

250
251
252
253
254
255
256
257
258
259
260
 * @returns {void}
 */
function commitSiteToGit(tag) {
    const currentDir = pwd();


    cd(SITE_DIR);
    exec("git add -A .");
    exec(`git commit -m "Added release blog post for ${tag}"`);
    exec(`git tag ${tag}`);
    exec("git fetch origin && git rebase origin/main");
fork icon0
star icon0
watch icon1

+ 119 other calls in file

44
45
46
47
48
49
50
51
52
53
    enableProfiler === undefined ? "false" : enableProfiler
  }`
);
console.log("--------------------");
shell.exec(`mkdir ${projectName}`);
shell.cd(`${projectName}`);
shell.exec(`git clone ${targetRepo} .`);

shell.exec(`git checkout -B ${branchName} remotes/origin/${branchName}`);
shell.exec("git checkout --orphan latest_branch");
fork icon0
star icon0
watch icon1

+ 17 other calls in file

146
147
148
149
150
151
152
153
154
155
156
  logger.info('Set up a new team and invited maintainers!');
}


function pushOriginalContents() {
  logger.trace('Setting up duplicate repo...');
  shell.cd('repo');
  // If we can't find the repo, clone it
  if (shell.cd(repository).code !== 0) {
    logger.debug("Can't find source repo locally. Cloning it...");
    shell.exec(`git clone ${originalUrl} ${repository}`);
fork icon0
star icon0
watch icon1

+ 9 other calls in file

93
94
95
96
97
98
99
100
101
if (code) {
	shell.exit(0);
}

// Navigate & validate that we are inside the new block directory.
const codeError = shell.cd(`${NEW_BLOCK_DIRECTORY_PATH}`).code;
if (codeError) {
	shell.exit(0);
}
fork icon0
star icon0
watch icon1

+ 17 other calls in file

334
335
336
337
338
339
340
341
342
343
function getBuildHash(dirName) {
    return __awaiter(this, void 0, void 0, function* () {
        return new Promise((resovle, reject) => {
            const workDir = path.normalize(`${dirName}/../../../`);
            console.log(`work dir`, workDir);
            shelljs.cd(workDir);
            shelljs.exec("git rev-parse --short HEAD", { encoding: "utf-8" }, (code, stdout, stderr) => {
                if (code !== 0) {
                    reject(stderr);
                }
fork icon0
star icon0
watch icon1

+ 6 other calls in file