mirror of
https://github.com/node-red/node-red.git
synced 2023-10-10 13:36:53 +02:00
Add ensureBuffer helper for nodes.
This commit is contained in:
parent
a3497a5fc7
commit
c0fcc20f23
12
red/util.js
12
red/util.js
@ -25,7 +25,19 @@ function ensureString(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 = {
|
||||
ensureString: ensureString,
|
||||
ensureBuffer: ensureBuffer,
|
||||
};
|
||||
|
||||
|
@ -37,5 +37,34 @@ describe("red/util", function() {
|
||||
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]);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user