UNPKG

2.07 kBJavaScriptView Raw
1var common = require('./common');
2var fs = require('fs');
3
4common.register('test', _test, {
5 cmdOptions: {
6 'b': 'block',
7 'c': 'character',
8 'd': 'directory',
9 'e': 'exists',
10 'f': 'file',
11 'L': 'link',
12 'p': 'pipe',
13 'S': 'socket',
14 },
15 wrapOutput: false,
16 allowGlobbing: false,
17});
18
19
20//@
21//@ ### test(expression)
22//@ Available expression primaries:
23//@
24//@ + `'-b', 'path'`: true if path is a block device
25//@ + `'-c', 'path'`: true if path is a character device
26//@ + `'-d', 'path'`: true if path is a directory
27//@ + `'-e', 'path'`: true if path exists
28//@ + `'-f', 'path'`: true if path is a regular file
29//@ + `'-L', 'path'`: true if path is a symbolic link
30//@ + `'-p', 'path'`: true if path is a pipe (FIFO)
31//@ + `'-S', 'path'`: true if path is a socket
32//@
33//@ Examples:
34//@
35//@ ```javascript
36//@ if (test('-d', path)) { /* do something with dir */ };
37//@ if (!test('-f', path)) continue; // skip if it's a regular file
38//@ ```
39//@
40//@ Evaluates expression using the available primaries and returns corresponding value.
41function _test(options, path) {
42 if (!path) common.error('no path given');
43
44 var canInterpret = false;
45 Object.keys(options).forEach(function (key) {
46 if (options[key] === true) {
47 canInterpret = true;
48 }
49 });
50
51 if (!canInterpret) common.error('could not interpret expression');
52
53 if (options.link) {
54 try {
55 return common.statNoFollowLinks(path).isSymbolicLink();
56 } catch (e) {
57 return false;
58 }
59 }
60
61 if (!fs.existsSync(path)) return false;
62
63 if (options.exists) return true;
64
65 var stats = common.statFollowLinks(path);
66
67 if (options.block) return stats.isBlockDevice();
68
69 if (options.character) return stats.isCharacterDevice();
70
71 if (options.directory) return stats.isDirectory();
72
73 if (options.file) return stats.isFile();
74
75 /* istanbul ignore next */
76 if (options.pipe) return stats.isFIFO();
77
78 /* istanbul ignore next */
79 if (options.socket) return stats.isSocket();
80
81 /* istanbul ignore next */
82 return false; // fallback
83} // test
84module.exports = _test;