UNPKG

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