0
# File System Information
1
2
File and directory information retrieval including existence checking, attribute inspection, path resolution, and working directory management.
3
4
## Capabilities
5
6
### Check Existence
7
8
Tests whether a remote file or directory exists and returns its type.
9
10
```javascript { .api }
11
/**
12
* Test if remote object exists and return its type
13
* @param remotePath - Path to remote object
14
* @returns Promise resolving to type string or false
15
* 'd' = directory, '-' = file, 'l' = symbolic link, false = does not exist
16
*/
17
exists(remotePath): Promise<Boolean|String>;
18
```
19
20
**Usage Examples:**
21
22
```javascript
23
// Check if file exists
24
const fileExists = await sftp.exists('/remote/file.txt');
25
if (fileExists === '-') {
26
console.log('File exists');
27
} else if (fileExists === false) {
28
console.log('File does not exist');
29
}
30
31
// Check if directory exists
32
const dirExists = await sftp.exists('/remote/folder');
33
if (dirExists === 'd') {
34
console.log('Directory exists');
35
}
36
37
// Check for symbolic link
38
const linkExists = await sftp.exists('/remote/symlink');
39
if (linkExists === 'l') {
40
console.log('Symbolic link exists');
41
}
42
43
// Conditional operations based on existence
44
const target = '/remote/config.json';
45
const exists = await sftp.exists(target);
46
if (exists === '-') {
47
// File exists, download it
48
await sftp.get(target, '/local/config.json');
49
} else if (exists === false) {
50
// File doesn't exist, create default
51
await sftp.put('/local/default-config.json', target);
52
}
53
```
54
55
### Get File Statistics
56
57
Retrieves detailed attributes for a remote file or directory, following symbolic links.
58
59
```javascript { .api }
60
/**
61
* Get file/directory attributes (follows symbolic links)
62
* @param remotePath - Path to remote object
63
* @returns Promise resolving to file statistics object
64
*/
65
stat(remotePath): Promise<Object>;
66
```
67
68
**Usage Examples:**
69
70
```javascript
71
// Get file statistics
72
const stats = await sftp.stat('/remote/file.txt');
73
console.log(`Size: ${stats.size} bytes`);
74
console.log(`Modified: ${new Date(stats.modifyTime)}`);
75
console.log(`Is file: ${stats.isFile}`);
76
console.log(`Permissions: ${stats.mode.toString(8)}`);
77
78
// Check if path is directory
79
const dirStats = await sftp.stat('/remote/folder');
80
if (dirStats.isDirectory) {
81
console.log('Path is a directory');
82
}
83
84
// File size comparison
85
const fileStats = await sftp.stat('/remote/large-file.dat');
86
if (fileStats.size > 100 * 1024 * 1024) {
87
console.log('File is larger than 100MB, using fastGet');
88
await sftp.fastGet('/remote/large-file.dat', '/local/large-file.dat');
89
}
90
```
91
92
### Get Link Statistics
93
94
Retrieves detailed attributes for a remote file or directory, NOT following symbolic links.
95
96
```javascript { .api }
97
/**
98
* Get file/directory attributes (does not follow symbolic links)
99
* @param remotePath - Path to remote object
100
* @returns Promise resolving to file statistics object
101
*/
102
lstat(remotePath): Promise<Object>;
103
```
104
105
**Usage Examples:**
106
107
```javascript
108
// Get symbolic link info (not target info)
109
const linkStats = await sftp.lstat('/remote/symlink');
110
if (linkStats.isSymbolicLink) {
111
console.log('This is a symbolic link');
112
// Get target info separately if needed
113
const targetStats = await sftp.stat('/remote/symlink');
114
console.log(`Link points to ${targetStats.isFile ? 'file' : 'directory'}`);
115
}
116
117
// Compare link vs target attributes
118
const linkInfo = await sftp.lstat('/remote/link-to-file');
119
const targetInfo = await sftp.stat('/remote/link-to-file');
120
console.log(`Link size: ${linkInfo.size}, Target size: ${targetInfo.size}`);
121
```
122
123
### Resolve Real Path
124
125
Returns the absolute path on the remote server, resolving relative paths and symbolic links.
126
127
```javascript { .api }
128
/**
129
* Get absolute path on remote server, resolving . and .. components
130
* @param remotePath - Path to resolve (can be relative)
131
* @param addListeners - Whether to add event listeners (default: true)
132
* @returns Promise resolving to absolute path string or empty string if not found
133
*/
134
realPath(remotePath, addListeners = true): Promise<String>;
135
```
136
137
**Usage Examples:**
138
139
```javascript
140
// Resolve relative path
141
const absolutePath = await sftp.realPath('../documents/file.txt');
142
console.log(`Absolute path: ${absolutePath}`);
143
144
// Resolve current directory
145
const currentDir = await sftp.realPath('.');
146
console.log(`Current directory: ${currentDir}`);
147
148
// Resolve symbolic link to actual path
149
const realPath = await sftp.realPath('/remote/symlink-to-file');
150
if (realPath) {
151
console.log(`Link resolves to: ${realPath}`);
152
} else {
153
console.log('Path does not exist');
154
}
155
156
// Path validation
157
const userInput = '../../../etc/passwd';
158
const resolved = await sftp.realPath(userInput);
159
if (resolved.startsWith('/home/user/')) {
160
console.log('Path is within allowed directory');
161
} else {
162
console.log('Path is outside allowed directory');
163
}
164
```
165
166
### Get Current Working Directory
167
168
Returns the current working directory path on the remote server.
169
170
```javascript { .api }
171
/**
172
* Get current working directory path
173
* @returns Promise resolving to current directory path
174
*/
175
cwd(): Promise<String>;
176
```
177
178
**Usage Examples:**
179
180
```javascript
181
// Get current directory
182
const currentDir = await sftp.cwd();
183
console.log(`Working directory: ${currentDir}`);
184
185
// Store current directory before changing
186
const originalDir = await sftp.cwd();
187
// ... perform operations in different directories ...
188
// Note: SFTP doesn't have a built-in cd command,
189
// but you can use absolute paths or realPath for navigation
190
191
// Build relative paths from current directory
192
const workingDir = await sftp.cwd();
193
const configFile = `${workingDir}/config/app.json`;
194
const exists = await sftp.exists(configFile);
195
```
196
197
## File Statistics Object
198
199
```javascript { .api }
200
interface FileStats {
201
mode: number; // File mode/permissions
202
uid: number; // Owner user ID
203
gid: number; // Owner group ID
204
size: number; // Size in bytes
205
accessTime: number; // Last access time (milliseconds since epoch)
206
modifyTime: number; // Last modify time (milliseconds since epoch)
207
isDirectory: boolean; // True if directory
208
isFile: boolean; // True if regular file
209
isBlockDevice: boolean; // True if block device
210
isCharacterDevice: boolean; // True if character device
211
isSymbolicLink: boolean; // True if symbolic link
212
isFIFO: boolean; // True if FIFO/named pipe
213
isSocket: boolean; // True if socket
214
}
215
```
216
217
## Common Usage Patterns
218
219
### Safe File Operations
220
221
```javascript
222
// Check before download
223
const remoteFile = '/remote/data.json';
224
const exists = await sftp.exists(remoteFile);
225
if (exists === '-') {
226
const stats = await sftp.stat(remoteFile);
227
if (stats.size > 0) {
228
await sftp.get(remoteFile, '/local/data.json');
229
} else {
230
console.log('Remote file is empty');
231
}
232
} else {
233
console.log('Remote file does not exist');
234
}
235
```
236
237
### Directory Traversal
238
239
```javascript
240
// Navigate and inspect directories
241
const currentDir = await sftp.cwd();
242
console.log(`Starting in: ${currentDir}`);
243
244
const targetDir = './subdirectory';
245
const absoluteTarget = await sftp.realPath(targetDir);
246
if (absoluteTarget) {
247
const stats = await sftp.stat(absoluteTarget);
248
if (stats.isDirectory) {
249
const files = await sftp.list(absoluteTarget);
250
console.log(`Directory contains ${files.length} items`);
251
}
252
}
253
```
254
255
### File Size and Date Filtering
256
257
```javascript
258
// Find large files modified recently
259
const files = await sftp.list('/remote/data');
260
const largeFreshFiles = [];
261
262
for (const file of files) {
263
if (file.type === '-') { // Regular file
264
const stats = await sftp.stat(`/remote/data/${file.name}`);
265
const dayOld = Date.now() - (24 * 60 * 60 * 1000);
266
const sizeMB = stats.size / (1024 * 1024);
267
268
if (stats.modifyTime > dayOld && sizeMB > 10) {
269
largeFreshFiles.push({
270
name: file.name,
271
size: sizeMB,
272
modified: new Date(stats.modifyTime)
273
});
274
}
275
}
276
}
277
```
278
279
### Permission Checking
280
281
```javascript
282
// Check file permissions
283
const stats = await sftp.stat('/remote/script.sh');
284
const permissions = stats.mode & parseInt('777', 8);
285
const isExecutable = (permissions & parseInt('111', 8)) !== 0;
286
287
console.log(`Permissions: ${permissions.toString(8)}`);
288
console.log(`Executable: ${isExecutable}`);
289
```
290
291
## Error Handling
292
293
File system information errors provide specific context:
294
295
- `ENOENT`: File or directory does not exist
296
- `EACCES`: Permission denied for stat operation
297
- `ERR_BAD_PATH`: Invalid path format
298
- `ERR_NOT_CONNECTED`: No active SFTP connection
299
- Network errors during remote file system access