Nessuna descrizione

nodejsUtils.js 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. if (Buffer.from && Buffer.from !== Uint8Array.from) {
  17. return Buffer.from(data, encoding);
  18. } else {
  19. if (typeof data === "number") {
  20. // Safeguard for old Node.js versions. On newer versions,
  21. // Buffer.from(number) / Buffer(number, encoding) already throw.
  22. throw new Error("The \"data\" argument must not be a number");
  23. }
  24. return new Buffer(data, encoding);
  25. }
  26. },
  27. /**
  28. * Create a new nodejs Buffer with the specified size.
  29. * @param {Integer} size the size of the buffer.
  30. * @return {Buffer} a new Buffer.
  31. */
  32. allocBuffer: function (size) {
  33. if (Buffer.alloc) {
  34. return Buffer.alloc(size);
  35. } else {
  36. var buf = new Buffer(size);
  37. buf.fill(0);
  38. return buf;
  39. }
  40. },
  41. /**
  42. * Find out if an object is a Buffer.
  43. * @param {Object} b the object to test.
  44. * @return {Boolean} true if the object is a Buffer, false otherwise.
  45. */
  46. isBuffer : function(b){
  47. return Buffer.isBuffer(b);
  48. },
  49. isStream : function (obj) {
  50. return obj &&
  51. typeof obj.on === "function" &&
  52. typeof obj.pause === "function" &&
  53. typeof obj.resume === "function";
  54. }
  55. };