1
0
mirror of https://github.com/node-red/node-red.git synced 2023-10-10 13:36:53 +02:00

Merge pull request #400 from hindessm/add-ensure-buffer-helper

Add ensureBuffer helper for nodes.
This commit is contained in:
Nick O'Leary 2014-09-10 13:33:23 +01:00
commit 429a87f88a
2 changed files with 41 additions and 0 deletions

View File

@ -25,7 +25,19 @@ function ensureString(o) {
return ""+o; return ""+o;
} }
function ensureBuffer(o) {
if (Buffer.isBuffer(o)) {
return o;
} else if (typeof o === "object") {
o = JSON.stringify(o);
} else if (typeof o !== "string") {
o = ""+o;
}
return new Buffer(o);
}
module.exports = { module.exports = {
ensureString: ensureString, ensureString: ensureString,
ensureBuffer: ensureBuffer,
}; };

View File

@ -37,5 +37,34 @@ describe("red/util", function() {
s.should.equal('123'); s.should.equal('123');
}); });
}); });
describe('ensureBuffer', function() {
it('Buffers are preserved', function() {
var b = new Buffer('');
util.ensureBuffer(b).should.equal(b);
});
it('string is converted', function() {
var b = util.ensureBuffer('foo');
var expected = new Buffer('foo');
for (var i = 0; i < expected.length; i++) {
b[i].should.equal(expected[i]);
}
Buffer.isBuffer(b).should.equal(true);
});
it('Object is converted to JSON', function() {
var obj = {foo: "bar"}
var b = util.ensureBuffer(obj);
Buffer.isBuffer(b).should.equal(true);
should.deepEqual(JSON.parse(b), obj);
});
it('stringifies other things', function() {
var b = util.ensureBuffer(123);
Buffer.isBuffer(b).should.equal(true);
var expected = new Buffer('123');
for (var i = 0; i < expected.length; i++) {
b[i].should.equal(expected[i]);
}
});
});
}); });