fsUtil.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. /**
  2. * Created by Tony on 2017/4/10.
  3. */
  4. let fs = require('fs');
  5. module.exports = {
  6. writeArrayToFile: function(arr, filePath) {
  7. if (arr && filePath && Array.isArray(arr)) {
  8. let chunks = [], len = 0;
  9. for (let i = 0; i < arr.length; i++) {
  10. let buffer = new Buffer(arr[i]);
  11. chunks.push(buffer);
  12. len += buffer.length;
  13. //
  14. }
  15. let resultBuffer = new Buffer(len);
  16. for(let i=0,size=chunks.length,pos=0;i<size;i++){
  17. chunks[i].copy(resultBuffer,pos);
  18. pos += chunks[i].length;
  19. }
  20. fs.writeFile(filePath, resultBuffer, function(err){
  21. if(err) throw err;
  22. //console.log('Write file: ' + filePath + ' ok!');
  23. });
  24. }
  25. },
  26. writeObjToFile: function(obj, filePath) {
  27. if (obj) {
  28. let arr = [];
  29. arr.push(JSON.stringify(obj));
  30. this.writeArrayToFile(arr, filePath);
  31. }
  32. }
  33. };