From 8da794f36a511d0447af4219f00e824c24a14073 Mon Sep 17 00:00:00 2001 From: Ethan Smith Date: Fri, 14 Apr 2017 15:47:34 -0400 Subject: [PATCH] Add support to 'scp' for Buffers --- README.md | 9 +++++++++ lib/scp.js | 16 ++++++++++++++++ test/client.test.js | 12 ++++++++++++ 3 files changed, 37 insertions(+) diff --git a/README.md b/README.md index 319c0d4..1aba496 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,15 @@ client.scp('file.txt', { }, function(err) {}) ``` +Copy a [`Buffer`](https://nodejs.org/api/buffer.html) to the server: + +```js +var buffer = new Buffer('Hello World\n'); + +client.scp(buffer, 'admin:password@example.com:port:/home/admin/', function(err) { +}); +``` + Copy a file to the server and rename it: ```js diff --git a/lib/scp.js b/lib/scp.js index 85e2675..ae69f82 100644 --- a/lib/scp.js +++ b/lib/scp.js @@ -73,6 +73,20 @@ function cp2remote(client, src, dest, callback) { } } +function cpBufferToRemote(client, buffer, dest, callback) { + var remote = client.parse(dest); + + client.write({ + destination: remote.path, + content: buffer + }, function(err) { + client.on('close', function closeHandler() { + callback(err); + client.removeListener('close', closeHandler); + }); + client.close(); + }); +} function cp2local(client, src, dest, callback) { var remote = client.parse(src); @@ -100,6 +114,8 @@ exports.scp = function(src, dest, client, callback) { var parsed = client.parse(src); if (parsed.host && parsed.path) { cp2local(client, parsed, dest, callback); + } else if (Buffer.isBuffer(src)) { + cpBufferToRemote(client, src, dest, callback); } else { cp2remote(client, src, dest, callback); } diff --git a/test/client.test.js b/test/client.test.js index 8d6bb68..fc3db91 100644 --- a/test/client.test.js +++ b/test/client.test.js @@ -28,6 +28,18 @@ describe('Client', function() { }); + it('returns non-string objects ', function() { + var stringBuffer = new Buffer('1234'), + arrayBuffer = new Buffer([ '1', '2', '3', '4' ]), + obj = { username: 'admin', host: 'example.com' }; + + expect(client.parse(false)).to.equal(false); + expect(client.parse(42)).to.equal(42); + expect(client.parse(stringBuffer)).to.equal(stringBuffer); + expect(client.parse(arrayBuffer)).to.equal(arrayBuffer); + expect(client.parse(obj)).to.equal(obj); + }); + }); describe('when calling from windows', function() {