ssh2-scp 1.0.2 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README-CN.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # ssh2-scp
2
2
 
3
- 通过 SSH2 会话进行远程文件系统操作(无需 SFTP)。
3
+ 通过 SSH2 会话进行远程文件系统操作/文件传输(无需 SFTP)。
4
4
 
5
5
  [English](./README.md)
6
6
 
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # ssh2-scp
2
2
 
3
- Remote file system operations over SSH2 session without SFTP
3
+ Remote file system operations/file transfer over SSH2 session without SFTP
4
4
 
5
5
  [中文](./README-CN.md)
6
6
 
@@ -2,9 +2,55 @@
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  class SshFs {
4
4
  session;
5
+ _chunkSize = null;
6
+ async getChunkSize() {
7
+ return this.detectChunkSize();
8
+ }
5
9
  constructor(session, _options) {
6
10
  this.session = session;
7
11
  }
12
+ async detectChunkSize() {
13
+ if (this._chunkSize !== null) {
14
+ return this._chunkSize;
15
+ }
16
+ const parseMemKb = (kb) => {
17
+ if (kb > 256 * 1024) {
18
+ return 4 * 1024;
19
+ } else if (kb > 128 * 1024) {
20
+ return 2 * 1024;
21
+ } else if (kb > 64 * 1024) {
22
+ return 1 * 1024;
23
+ }
24
+ return 512;
25
+ };
26
+ try {
27
+ const output = await this.runCmd("free -b");
28
+ const lines = output.trim().split("\n");
29
+ const memLine = lines.find((l) => l.startsWith("Mem:"));
30
+ if (memLine) {
31
+ const parts = memLine.trim().split(/\s+/);
32
+ const totalMemKb = parseInt(parts[1], 10);
33
+ this._chunkSize = parseMemKb(totalMemKb);
34
+ return this._chunkSize;
35
+ }
36
+ } catch (err) {
37
+ console.error("[ssh-fs] detectChunkSize: free -b failed", err);
38
+ }
39
+ try {
40
+ const output = await this.runCmd("cat /proc/meminfo");
41
+ const memTotalLine = output.split("\n").find((l) => l.startsWith("MemTotal:"));
42
+ if (memTotalLine) {
43
+ const kb = parseInt(memTotalLine.split(":")[1].trim(), 10);
44
+ this._chunkSize = parseMemKb(kb);
45
+ return this._chunkSize;
46
+ }
47
+ } catch (err) {
48
+ console.error("[ssh-fs] detectChunkSize: /proc/meminfo failed", err);
49
+ }
50
+ this._chunkSize = 1 * 1024;
51
+ console.error("[ssh-fs] detectChunkSize: using default chunkSize");
52
+ return this._chunkSize;
53
+ }
8
54
  getExecOpts() {
9
55
  return {};
10
56
  }
@@ -12,6 +58,30 @@ class SshFs {
12
58
  const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
13
59
  return months.indexOf(month);
14
60
  }
61
+ parseMode(modeStr) {
62
+ const permMap = {
63
+ "---": 0,
64
+ "--x": 1,
65
+ "-w-": 2,
66
+ "-wx": 3,
67
+ "r--": 4,
68
+ "r-x": 5,
69
+ "rw-": 6,
70
+ "rwx": 7
71
+ };
72
+ const perms = modeStr.slice(1, 10);
73
+ const owner = permMap[perms.slice(0, 3)] || 0;
74
+ const group = permMap[perms.slice(3, 6)] || 0;
75
+ const other = permMap[perms.slice(6, 9)] || 0;
76
+ let fileType = 32768;
77
+ if (modeStr.startsWith("d")) fileType = 16384;
78
+ else if (modeStr.startsWith("l")) fileType = 40960;
79
+ else if (modeStr.startsWith("c")) fileType = 8192;
80
+ else if (modeStr.startsWith("b")) fileType = 24576;
81
+ else if (modeStr.startsWith("p")) fileType = 4096;
82
+ else if (modeStr.startsWith("s")) fileType = 49152;
83
+ return fileType | owner << 6 | group << 3 | other;
84
+ }
15
85
  runCmd(cmd, timeout = 3e4) {
16
86
  return new Promise((resolve, reject) => {
17
87
  let timeoutId;
@@ -115,11 +185,13 @@ class SshFs {
115
185
  });
116
186
  }
117
187
  async getFolderSize(folderPath) {
118
- const output = await this.runExec(`du -sh "${folderPath}" && find "${folderPath}" -type f | wc -l`);
119
- const lines = output.trim().split("\n");
120
- const size = lines[0]?.split(" ")[0] || "0";
121
- const count = parseInt(lines[1] || "0", 10);
122
- return { size, count };
188
+ try {
189
+ const output = await this.runCmd(`du -sh "${folderPath}"`);
190
+ const size = output.trim().split(" ")[0] || "0";
191
+ return { size, count: 0 };
192
+ } catch {
193
+ return { size: "0", count: 0 };
194
+ }
123
195
  }
124
196
  async listFiles(remotePath) {
125
197
  const output = await this.runCmd(`ls -la "${remotePath}"`);
@@ -176,9 +248,9 @@ class SshFs {
176
248
  }
177
249
  async stat(remotePath) {
178
250
  const isSymlink = await this.runCmd(`test -L "${remotePath}" && echo 1 || echo 0`).then((r) => r.trim() === "1");
179
- const output = await this.runCmd(`stat -c '%s %h %u %g %Y %Y %a' "${remotePath}"`);
251
+ const output = await this.runCmd(`ls -la "${remotePath}"`);
180
252
  const parts = output.trim().split(/\s+/);
181
- if (parts.length < 7) {
253
+ if (parts.length < 9) {
182
254
  return {
183
255
  size: 0,
184
256
  mode: 0,
@@ -195,36 +267,39 @@ class SshFs {
195
267
  isSocket: () => false
196
268
  };
197
269
  }
198
- const [size, _nlink, uid, gid, atime, mtime, modeOct] = parts;
199
- const mode = parseInt(modeOct, 8);
270
+ const size = parseInt(parts[4], 10);
271
+ const modeStr = parts[0];
272
+ const mode = this.parseMode(modeStr);
273
+ const uid = parseInt(parts[2], 10);
274
+ const gid = parseInt(parts[3], 10);
200
275
  return {
201
- size: parseInt(size, 10),
276
+ size,
202
277
  mode,
203
- uid: parseInt(uid, 10),
204
- gid: parseInt(gid, 10),
205
- atime: parseInt(atime, 10) * 1e3,
206
- mtime: parseInt(mtime, 10) * 1e3,
207
- isFile: () => (mode & 61440) === 32768,
208
- isDirectory: () => (mode & 61440) === 16384,
278
+ uid,
279
+ gid,
280
+ atime: 0,
281
+ mtime: 0,
282
+ isFile: () => modeStr.startsWith("-"),
283
+ isDirectory: () => modeStr.startsWith("d"),
209
284
  isSymbolicLink: () => isSymlink,
210
- isBlockDevice: () => (mode & 61440) === 24576,
211
- isCharacterDevice: () => (mode & 61440) === 8192,
212
- isFIFO: () => (mode & 61440) === 4096,
213
- isSocket: () => (mode & 61440) === 49152
285
+ isBlockDevice: () => modeStr.startsWith("b"),
286
+ isCharacterDevice: () => modeStr.startsWith("c"),
287
+ isFIFO: () => modeStr.startsWith("p"),
288
+ isSocket: () => modeStr.startsWith("s")
214
289
  };
215
290
  }
216
291
  readlink(remotePath) {
217
292
  return this.runCmd(`readlink "${remotePath}"`).then((output) => output.trim());
218
293
  }
219
294
  realpath(remotePath) {
220
- return this.runCmd(`realpath "${remotePath}"`).then((output) => output.trim());
295
+ return this.runCmd(`readlink -f "${remotePath}"`).then((output) => output.trim()).catch(() => this.runCmd(`cd "${remotePath}" && pwd`).then((output) => output.trim()));
221
296
  }
222
297
  async lstat(remotePath) {
223
298
  const output = await this.runCmd(`ls -ld "${remotePath}"`);
224
299
  const isSymlink = output.trim().startsWith("l");
225
- const statOutput = await this.runCmd(`stat -c '%s %h %u %g %Y %Y %a' "${remotePath}"`);
226
- const parts = statOutput.trim().split(/\s+/);
227
- if (parts.length < 7) {
300
+ const lsOutput = await this.runCmd(`ls -la "${remotePath}"`);
301
+ const parts = lsOutput.trim().split(/\s+/);
302
+ if (parts.length < 9) {
228
303
  return {
229
304
  size: 0,
230
305
  mode: 0,
@@ -241,22 +316,25 @@ class SshFs {
241
316
  isSocket: () => false
242
317
  };
243
318
  }
244
- const [size, _nlink, uid, gid, atime, mtime, modeOct] = parts;
245
- const mode = parseInt(modeOct, 8);
319
+ const size = parseInt(parts[4], 10);
320
+ const modeStr = parts[0];
321
+ const mode = this.parseMode(modeStr);
322
+ const uid = parseInt(parts[2], 10);
323
+ const gid = parseInt(parts[3], 10);
246
324
  return {
247
- size: parseInt(size, 10),
325
+ size,
248
326
  mode,
249
- uid: parseInt(uid, 10),
250
- gid: parseInt(gid, 10),
251
- atime: parseInt(atime, 10) * 1e3,
252
- mtime: parseInt(mtime, 10) * 1e3,
253
- isFile: () => !isSymlink && (mode & 61440) === 32768,
254
- isDirectory: () => !isSymlink && (mode & 61440) === 16384,
327
+ uid,
328
+ gid,
329
+ atime: 0,
330
+ mtime: 0,
331
+ isFile: () => !isSymlink && modeStr.startsWith("-"),
332
+ isDirectory: () => !isSymlink && modeStr.startsWith("d"),
255
333
  isSymbolicLink: () => isSymlink,
256
- isBlockDevice: () => (mode & 61440) === 24576,
257
- isCharacterDevice: () => (mode & 61440) === 8192,
258
- isFIFO: () => (mode & 61440) === 4096,
259
- isSocket: () => (mode & 61440) === 49152
334
+ isBlockDevice: () => modeStr.startsWith("b"),
335
+ isCharacterDevice: () => modeStr.startsWith("c"),
336
+ isFIFO: () => modeStr.startsWith("p"),
337
+ isSocket: () => modeStr.startsWith("s")
260
338
  };
261
339
  }
262
340
  chmod(remotePath, mode) {
@@ -272,35 +350,42 @@ class SshFs {
272
350
  return this.rmCmd(remotePath);
273
351
  }
274
352
  async readFile(remotePath, options) {
275
- const chunkSize = options?.chunkSize ?? 64 * 1024;
276
- const fileSizeOutput = await this.runCmd(`stat -c %s "${remotePath}"`);
277
- const fileSize = parseInt(fileSizeOutput.trim(), 10);
353
+ const defaultChunkSize = await this.detectChunkSize();
354
+ const chunkSize = options?.chunkSize ?? defaultChunkSize;
355
+ const lsOutput = await this.runCmd(`ls -la "${remotePath}"`);
356
+ const parts = lsOutput.trim().split(/\s+/);
357
+ const fileSize = parts.length >= 5 ? parseInt(parts[4], 10) : 0;
278
358
  if (fileSize <= chunkSize) {
279
359
  const output = await this.runCmd(`cat "${remotePath}"`);
280
- return Buffer.from(output, "binary");
360
+ return output;
281
361
  }
282
362
  const chunks = [];
283
363
  for (let offset = 0; offset < fileSize; offset += chunkSize) {
284
- const cmd = `dd if="${remotePath}" bs=1K skip=${Math.floor(offset / 1024)} count=${Math.ceil(chunkSize / 1024)} 2>/dev/null`;
285
- const chunkOutput = await this.runCmd(cmd);
286
- if (chunkOutput) {
287
- chunks.push(Buffer.from(chunkOutput, "binary"));
364
+ try {
365
+ const cmd = `dd if="${remotePath}" bs=1K skip=${Math.floor(offset / 1024)} count=${Math.ceil(chunkSize / 1024)} 2>/dev/null`;
366
+ const chunkOutput = await this.runCmd(cmd);
367
+ if (chunkOutput) {
368
+ chunks.push(chunkOutput);
369
+ }
370
+ } catch {
371
+ return this.runCmd(`cat "${remotePath}"`);
288
372
  }
289
373
  }
290
- return Buffer.concat(chunks);
374
+ return chunks.join("");
291
375
  }
292
376
  async writeFile(remotePath, str, mode, _options) {
293
- const data = typeof str === "string" ? Buffer.from(str) : str;
294
- const sizeThreshold = 64 * 1024;
377
+ const defaultChunkSize = await this.detectChunkSize();
378
+ const data = Buffer.from(str);
379
+ const sizeThreshold = defaultChunkSize;
295
380
  if (data.length <= sizeThreshold) {
296
- const escapedContent = data.toString("binary").replace(/'/g, "'\\''");
381
+ const escapedContent = str.replace(/'/g, "'\\''");
297
382
  const cmd = `printf '%s' '${escapedContent}' > "${remotePath}"`;
298
383
  await this.runCmd(cmd);
299
384
  } else {
300
385
  const tempBase = `/tmp/ssh-fs-${Date.now()}`;
301
386
  await this.runCmd(`mkdir -p "${tempBase}"`);
302
387
  try {
303
- const chunkSize = 64 * 1024;
388
+ const chunkSize = defaultChunkSize;
304
389
  for (let i = 0; i < data.length; i += chunkSize) {
305
390
  const chunk = data.slice(i, i + chunkSize);
306
391
  const chunkFile = `${tempBase}/c${Math.floor(i / chunkSize)}`;
@@ -26,10 +26,12 @@ class Transfer {
26
26
  chunkSize;
27
27
  state;
28
28
  aborted = false;
29
+ sshFs;
29
30
  constructor(sshFs, options) {
31
+ this.sshFs = sshFs;
30
32
  this.session = sshFs.session;
31
33
  this.options = options;
32
- this.chunkSize = options.chunkSize || 32768;
34
+ this.chunkSize = options.chunkSize || 4096;
33
35
  this.state = {
34
36
  transferred: 0,
35
37
  total: 0,
@@ -41,6 +43,9 @@ class Transfer {
41
43
  if (this.state.completed || this.state.error || this.aborted) {
42
44
  return;
43
45
  }
46
+ if (!this.options.chunkSize) {
47
+ this.chunkSize = await this.sshFs.getChunkSize();
48
+ }
44
49
  const isDownload = this.options.type === "download";
45
50
  try {
46
51
  if (isDownload) {
@@ -20,9 +20,13 @@ export declare interface FileInfo {
20
20
 
21
21
  export declare class SshFs {
22
22
  private session;
23
+ private _chunkSize;
24
+ getChunkSize(): Promise<number>;
23
25
  constructor(session: Client, _options?: SshFsOptions);
26
+ private detectChunkSize;
24
27
  private getExecOpts;
25
28
  private getMonthIndex;
29
+ private parseMode;
26
30
  private runCmd;
27
31
  private rmFolderCmd;
28
32
  private rmCmd;
@@ -53,8 +57,8 @@ export declare class SshFs {
53
57
  rm(remotePath: string): Promise<string>;
54
58
  readFile(remotePath: string, options?: {
55
59
  chunkSize?: number;
56
- }): Promise<Buffer>;
57
- writeFile(remotePath: string, str: Buffer | string, mode?: number, _options?: {
60
+ }): Promise<string>;
61
+ writeFile(remotePath: string, str: string, mode?: number, _options?: {
58
62
  chunkSize?: number;
59
63
  }): Promise<void>;
60
64
  }
@@ -1,8 +1,54 @@
1
1
  class SshFs {
2
2
  session;
3
+ _chunkSize = null;
4
+ async getChunkSize() {
5
+ return this.detectChunkSize();
6
+ }
3
7
  constructor(session, _options) {
4
8
  this.session = session;
5
9
  }
10
+ async detectChunkSize() {
11
+ if (this._chunkSize !== null) {
12
+ return this._chunkSize;
13
+ }
14
+ const parseMemKb = (kb) => {
15
+ if (kb > 256 * 1024) {
16
+ return 4 * 1024;
17
+ } else if (kb > 128 * 1024) {
18
+ return 2 * 1024;
19
+ } else if (kb > 64 * 1024) {
20
+ return 1 * 1024;
21
+ }
22
+ return 512;
23
+ };
24
+ try {
25
+ const output = await this.runCmd("free -b");
26
+ const lines = output.trim().split("\n");
27
+ const memLine = lines.find((l) => l.startsWith("Mem:"));
28
+ if (memLine) {
29
+ const parts = memLine.trim().split(/\s+/);
30
+ const totalMemKb = parseInt(parts[1], 10);
31
+ this._chunkSize = parseMemKb(totalMemKb);
32
+ return this._chunkSize;
33
+ }
34
+ } catch (err) {
35
+ console.error("[ssh-fs] detectChunkSize: free -b failed", err);
36
+ }
37
+ try {
38
+ const output = await this.runCmd("cat /proc/meminfo");
39
+ const memTotalLine = output.split("\n").find((l) => l.startsWith("MemTotal:"));
40
+ if (memTotalLine) {
41
+ const kb = parseInt(memTotalLine.split(":")[1].trim(), 10);
42
+ this._chunkSize = parseMemKb(kb);
43
+ return this._chunkSize;
44
+ }
45
+ } catch (err) {
46
+ console.error("[ssh-fs] detectChunkSize: /proc/meminfo failed", err);
47
+ }
48
+ this._chunkSize = 1 * 1024;
49
+ console.error("[ssh-fs] detectChunkSize: using default chunkSize");
50
+ return this._chunkSize;
51
+ }
6
52
  getExecOpts() {
7
53
  return {};
8
54
  }
@@ -10,6 +56,30 @@ class SshFs {
10
56
  const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
11
57
  return months.indexOf(month);
12
58
  }
59
+ parseMode(modeStr) {
60
+ const permMap = {
61
+ "---": 0,
62
+ "--x": 1,
63
+ "-w-": 2,
64
+ "-wx": 3,
65
+ "r--": 4,
66
+ "r-x": 5,
67
+ "rw-": 6,
68
+ "rwx": 7
69
+ };
70
+ const perms = modeStr.slice(1, 10);
71
+ const owner = permMap[perms.slice(0, 3)] || 0;
72
+ const group = permMap[perms.slice(3, 6)] || 0;
73
+ const other = permMap[perms.slice(6, 9)] || 0;
74
+ let fileType = 32768;
75
+ if (modeStr.startsWith("d")) fileType = 16384;
76
+ else if (modeStr.startsWith("l")) fileType = 40960;
77
+ else if (modeStr.startsWith("c")) fileType = 8192;
78
+ else if (modeStr.startsWith("b")) fileType = 24576;
79
+ else if (modeStr.startsWith("p")) fileType = 4096;
80
+ else if (modeStr.startsWith("s")) fileType = 49152;
81
+ return fileType | owner << 6 | group << 3 | other;
82
+ }
13
83
  runCmd(cmd, timeout = 3e4) {
14
84
  return new Promise((resolve, reject) => {
15
85
  let timeoutId;
@@ -113,11 +183,13 @@ class SshFs {
113
183
  });
114
184
  }
115
185
  async getFolderSize(folderPath) {
116
- const output = await this.runExec(`du -sh "${folderPath}" && find "${folderPath}" -type f | wc -l`);
117
- const lines = output.trim().split("\n");
118
- const size = lines[0]?.split(" ")[0] || "0";
119
- const count = parseInt(lines[1] || "0", 10);
120
- return { size, count };
186
+ try {
187
+ const output = await this.runCmd(`du -sh "${folderPath}"`);
188
+ const size = output.trim().split(" ")[0] || "0";
189
+ return { size, count: 0 };
190
+ } catch {
191
+ return { size: "0", count: 0 };
192
+ }
121
193
  }
122
194
  async listFiles(remotePath) {
123
195
  const output = await this.runCmd(`ls -la "${remotePath}"`);
@@ -174,9 +246,9 @@ class SshFs {
174
246
  }
175
247
  async stat(remotePath) {
176
248
  const isSymlink = await this.runCmd(`test -L "${remotePath}" && echo 1 || echo 0`).then((r) => r.trim() === "1");
177
- const output = await this.runCmd(`stat -c '%s %h %u %g %Y %Y %a' "${remotePath}"`);
249
+ const output = await this.runCmd(`ls -la "${remotePath}"`);
178
250
  const parts = output.trim().split(/\s+/);
179
- if (parts.length < 7) {
251
+ if (parts.length < 9) {
180
252
  return {
181
253
  size: 0,
182
254
  mode: 0,
@@ -193,36 +265,39 @@ class SshFs {
193
265
  isSocket: () => false
194
266
  };
195
267
  }
196
- const [size, _nlink, uid, gid, atime, mtime, modeOct] = parts;
197
- const mode = parseInt(modeOct, 8);
268
+ const size = parseInt(parts[4], 10);
269
+ const modeStr = parts[0];
270
+ const mode = this.parseMode(modeStr);
271
+ const uid = parseInt(parts[2], 10);
272
+ const gid = parseInt(parts[3], 10);
198
273
  return {
199
- size: parseInt(size, 10),
274
+ size,
200
275
  mode,
201
- uid: parseInt(uid, 10),
202
- gid: parseInt(gid, 10),
203
- atime: parseInt(atime, 10) * 1e3,
204
- mtime: parseInt(mtime, 10) * 1e3,
205
- isFile: () => (mode & 61440) === 32768,
206
- isDirectory: () => (mode & 61440) === 16384,
276
+ uid,
277
+ gid,
278
+ atime: 0,
279
+ mtime: 0,
280
+ isFile: () => modeStr.startsWith("-"),
281
+ isDirectory: () => modeStr.startsWith("d"),
207
282
  isSymbolicLink: () => isSymlink,
208
- isBlockDevice: () => (mode & 61440) === 24576,
209
- isCharacterDevice: () => (mode & 61440) === 8192,
210
- isFIFO: () => (mode & 61440) === 4096,
211
- isSocket: () => (mode & 61440) === 49152
283
+ isBlockDevice: () => modeStr.startsWith("b"),
284
+ isCharacterDevice: () => modeStr.startsWith("c"),
285
+ isFIFO: () => modeStr.startsWith("p"),
286
+ isSocket: () => modeStr.startsWith("s")
212
287
  };
213
288
  }
214
289
  readlink(remotePath) {
215
290
  return this.runCmd(`readlink "${remotePath}"`).then((output) => output.trim());
216
291
  }
217
292
  realpath(remotePath) {
218
- return this.runCmd(`realpath "${remotePath}"`).then((output) => output.trim());
293
+ return this.runCmd(`readlink -f "${remotePath}"`).then((output) => output.trim()).catch(() => this.runCmd(`cd "${remotePath}" && pwd`).then((output) => output.trim()));
219
294
  }
220
295
  async lstat(remotePath) {
221
296
  const output = await this.runCmd(`ls -ld "${remotePath}"`);
222
297
  const isSymlink = output.trim().startsWith("l");
223
- const statOutput = await this.runCmd(`stat -c '%s %h %u %g %Y %Y %a' "${remotePath}"`);
224
- const parts = statOutput.trim().split(/\s+/);
225
- if (parts.length < 7) {
298
+ const lsOutput = await this.runCmd(`ls -la "${remotePath}"`);
299
+ const parts = lsOutput.trim().split(/\s+/);
300
+ if (parts.length < 9) {
226
301
  return {
227
302
  size: 0,
228
303
  mode: 0,
@@ -239,22 +314,25 @@ class SshFs {
239
314
  isSocket: () => false
240
315
  };
241
316
  }
242
- const [size, _nlink, uid, gid, atime, mtime, modeOct] = parts;
243
- const mode = parseInt(modeOct, 8);
317
+ const size = parseInt(parts[4], 10);
318
+ const modeStr = parts[0];
319
+ const mode = this.parseMode(modeStr);
320
+ const uid = parseInt(parts[2], 10);
321
+ const gid = parseInt(parts[3], 10);
244
322
  return {
245
- size: parseInt(size, 10),
323
+ size,
246
324
  mode,
247
- uid: parseInt(uid, 10),
248
- gid: parseInt(gid, 10),
249
- atime: parseInt(atime, 10) * 1e3,
250
- mtime: parseInt(mtime, 10) * 1e3,
251
- isFile: () => !isSymlink && (mode & 61440) === 32768,
252
- isDirectory: () => !isSymlink && (mode & 61440) === 16384,
325
+ uid,
326
+ gid,
327
+ atime: 0,
328
+ mtime: 0,
329
+ isFile: () => !isSymlink && modeStr.startsWith("-"),
330
+ isDirectory: () => !isSymlink && modeStr.startsWith("d"),
253
331
  isSymbolicLink: () => isSymlink,
254
- isBlockDevice: () => (mode & 61440) === 24576,
255
- isCharacterDevice: () => (mode & 61440) === 8192,
256
- isFIFO: () => (mode & 61440) === 4096,
257
- isSocket: () => (mode & 61440) === 49152
332
+ isBlockDevice: () => modeStr.startsWith("b"),
333
+ isCharacterDevice: () => modeStr.startsWith("c"),
334
+ isFIFO: () => modeStr.startsWith("p"),
335
+ isSocket: () => modeStr.startsWith("s")
258
336
  };
259
337
  }
260
338
  chmod(remotePath, mode) {
@@ -270,35 +348,42 @@ class SshFs {
270
348
  return this.rmCmd(remotePath);
271
349
  }
272
350
  async readFile(remotePath, options) {
273
- const chunkSize = options?.chunkSize ?? 64 * 1024;
274
- const fileSizeOutput = await this.runCmd(`stat -c %s "${remotePath}"`);
275
- const fileSize = parseInt(fileSizeOutput.trim(), 10);
351
+ const defaultChunkSize = await this.detectChunkSize();
352
+ const chunkSize = options?.chunkSize ?? defaultChunkSize;
353
+ const lsOutput = await this.runCmd(`ls -la "${remotePath}"`);
354
+ const parts = lsOutput.trim().split(/\s+/);
355
+ const fileSize = parts.length >= 5 ? parseInt(parts[4], 10) : 0;
276
356
  if (fileSize <= chunkSize) {
277
357
  const output = await this.runCmd(`cat "${remotePath}"`);
278
- return Buffer.from(output, "binary");
358
+ return output;
279
359
  }
280
360
  const chunks = [];
281
361
  for (let offset = 0; offset < fileSize; offset += chunkSize) {
282
- const cmd = `dd if="${remotePath}" bs=1K skip=${Math.floor(offset / 1024)} count=${Math.ceil(chunkSize / 1024)} 2>/dev/null`;
283
- const chunkOutput = await this.runCmd(cmd);
284
- if (chunkOutput) {
285
- chunks.push(Buffer.from(chunkOutput, "binary"));
362
+ try {
363
+ const cmd = `dd if="${remotePath}" bs=1K skip=${Math.floor(offset / 1024)} count=${Math.ceil(chunkSize / 1024)} 2>/dev/null`;
364
+ const chunkOutput = await this.runCmd(cmd);
365
+ if (chunkOutput) {
366
+ chunks.push(chunkOutput);
367
+ }
368
+ } catch {
369
+ return this.runCmd(`cat "${remotePath}"`);
286
370
  }
287
371
  }
288
- return Buffer.concat(chunks);
372
+ return chunks.join("");
289
373
  }
290
374
  async writeFile(remotePath, str, mode, _options) {
291
- const data = typeof str === "string" ? Buffer.from(str) : str;
292
- const sizeThreshold = 64 * 1024;
375
+ const defaultChunkSize = await this.detectChunkSize();
376
+ const data = Buffer.from(str);
377
+ const sizeThreshold = defaultChunkSize;
293
378
  if (data.length <= sizeThreshold) {
294
- const escapedContent = data.toString("binary").replace(/'/g, "'\\''");
379
+ const escapedContent = str.replace(/'/g, "'\\''");
295
380
  const cmd = `printf '%s' '${escapedContent}' > "${remotePath}"`;
296
381
  await this.runCmd(cmd);
297
382
  } else {
298
383
  const tempBase = `/tmp/ssh-fs-${Date.now()}`;
299
384
  await this.runCmd(`mkdir -p "${tempBase}"`);
300
385
  try {
301
- const chunkSize = 64 * 1024;
386
+ const chunkSize = defaultChunkSize;
302
387
  for (let i = 0; i < data.length; i += chunkSize) {
303
388
  const chunk = data.slice(i, i + chunkSize);
304
389
  const chunkFile = `${tempBase}/c${Math.floor(i / chunkSize)}`;
@@ -18,9 +18,13 @@ declare interface FileInfo {
18
18
 
19
19
  declare class SshFs {
20
20
  private session;
21
+ private _chunkSize;
22
+ getChunkSize(): Promise<number>;
21
23
  constructor(session: Client, _options?: SshFsOptions);
24
+ private detectChunkSize;
22
25
  private getExecOpts;
23
26
  private getMonthIndex;
27
+ private parseMode;
24
28
  private runCmd;
25
29
  private rmFolderCmd;
26
30
  private rmCmd;
@@ -51,8 +55,8 @@ declare class SshFs {
51
55
  rm(remotePath: string): Promise<string>;
52
56
  readFile(remotePath: string, options?: {
53
57
  chunkSize?: number;
54
- }): Promise<Buffer>;
55
- writeFile(remotePath: string, str: Buffer | string, mode?: number, _options?: {
58
+ }): Promise<string>;
59
+ writeFile(remotePath: string, str: string, mode?: number, _options?: {
56
60
  chunkSize?: number;
57
61
  }): Promise<void>;
58
62
  }
@@ -82,6 +86,7 @@ export declare class Transfer {
82
86
  private chunkSize;
83
87
  private state;
84
88
  private aborted;
89
+ private sshFs;
85
90
  constructor(sshFs: SshFs, options: TransferOptions);
86
91
  startTransfer(): Promise<void>;
87
92
  private getRemoteFileSize;
@@ -6,10 +6,12 @@ class Transfer {
6
6
  chunkSize;
7
7
  state;
8
8
  aborted = false;
9
+ sshFs;
9
10
  constructor(sshFs, options) {
11
+ this.sshFs = sshFs;
10
12
  this.session = sshFs.session;
11
13
  this.options = options;
12
- this.chunkSize = options.chunkSize || 32768;
14
+ this.chunkSize = options.chunkSize || 4096;
13
15
  this.state = {
14
16
  transferred: 0,
15
17
  total: 0,
@@ -21,6 +23,9 @@ class Transfer {
21
23
  if (this.state.completed || this.state.error || this.aborted) {
22
24
  return;
23
25
  }
26
+ if (!this.options.chunkSize) {
27
+ this.chunkSize = await this.sshFs.getChunkSize();
28
+ }
24
29
  const isDownload = this.options.type === "download";
25
30
  try {
26
31
  if (isDownload) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ssh2-scp",
3
- "version": "1.0.2",
3
+ "version": "2.0.3",
4
4
  "description": "Remote file system operations over SSH2 session without SFTP",
5
5
  "scripts": {
6
6
  "build": "npm run build:esm && npm run build:cjs",
@@ -46,6 +46,7 @@
46
46
  "@types/node": "^20.10.0",
47
47
  "@types/ssh2": "^1.11.0",
48
48
  "@types/tar": "^6.1.0",
49
+ "dotenv": "^16.4.0",
49
50
  "ssh2": "^1.15.0",
50
51
  "tar": "^6.2.0",
51
52
  "typescript": "^5.3.0",