UNPKG

925 BJavaScriptView Raw
1var os = require('os');
2var common = require('./common');
3
4common.register('cd', _cd, {});
5
6//@
7//@ ### cd([dir])
8//@ Changes to directory `dir` for the duration of the script. Changes to home
9//@ directory if no argument is supplied.
10function _cd(options, dir) {
11 if (!dir) dir = os.homedir();
12
13 if (dir === '-') {
14 if (!process.env.OLDPWD) {
15 common.error('could not find previous directory');
16 } else {
17 dir = process.env.OLDPWD;
18 }
19 }
20
21 try {
22 var curDir = process.cwd();
23 process.chdir(dir);
24 process.env.OLDPWD = curDir;
25 } catch (e) {
26 // something went wrong, let's figure out the error
27 var err;
28 try {
29 common.statFollowLinks(dir); // if this succeeds, it must be some sort of file
30 err = 'not a directory: ' + dir;
31 } catch (e2) {
32 err = 'no such file or directory: ' + dir;
33 }
34 if (err) common.error(err);
35 }
36 return '';
37}
38module.exports = _cd;