nodejsUtils.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. module.exports = {
  3. /**
  4. * True if this is running in Nodejs, will be undefined in a browser.
  5. * In a browser, browserify won't include this file and the whole module
  6. * will be resolved an empty object.
  7. */
  8. isNode : typeof Buffer !== "undefined",
  9. /**
  10. * Create a new nodejs Buffer from an existing content.
  11. * @param {Object} data the data to pass to the constructor.
  12. * @param {String} encoding the encoding to use.
  13. * @return {Buffer} a new Buffer.
  14. */
  15. newBufferFrom: function(data, encoding) {
  16. // XXX We can't use `Buffer.from` which comes from `Uint8Array.from`
  17. // in nodejs v4 (< v.4.5). It's not the expected implementation (and
  18. // has a different signature).
  19. // see https://github.com/nodejs/node/issues/8053
  20. // A condition on nodejs' version won't solve the issue as we don't
  21. // control the Buffer polyfills that may or may not be used.
  22. return new Buffer(data, encoding);
  23. },
  24. /**
  25. * Create a new nodejs Buffer with the specified size.
  26. * @param {Integer} size the size of the buffer.
  27. * @return {Buffer} a new Buffer.
  28. */
  29. allocBuffer: function (size) {
  30. if (Buffer.alloc) {
  31. return Buffer.alloc(size);
  32. } else {
  33. return new Buffer(size);
  34. }
  35. },
  36. /**
  37. * Find out if an object is a Buffer.
  38. * @param {Object} b the object to test.
  39. * @return {Boolean} true if the object is a Buffer, false otherwise.
  40. */
  41. isBuffer : function(b){
  42. return Buffer.isBuffer(b);
  43. },
  44. isStream : function (obj) {
  45. return obj &&
  46. typeof obj.on === "function" &&
  47. typeof obj.pause === "function" &&
  48. typeof obj.resume === "function";
  49. }
  50. };