UNPKG

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