1
0

write.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import path from "../../../lib/path.js"
  2. import getAbsolutePathForApp from '../utils/getAbsolutePathForApp.js';
  3. const write = async function (targetPath, data, options = {}) {
  4. // targetPath is required
  5. if(!targetPath){
  6. throw new Error({ code: 'NO_TARGET_PATH', message: 'No target path provided.' });
  7. }
  8. // if targetPath is a File
  9. if(targetPath instanceof File && data === undefined){
  10. data = targetPath;
  11. targetPath = data.name;
  12. }
  13. // strict mode will cause the upload to fail if even one operation fails
  14. // for example, if one of the files in a folder fails to upload, the entire upload will fail
  15. // since write is a wrapper around upload to handle single-file uploads, we need to pass the strict option to upload
  16. options.strict = true;
  17. // by default, we want to overwrite existing files
  18. options.overwrite = options.overwrite ?? true;
  19. // if overwrite is true and dedupeName is not provided, set dedupeName to false
  20. if(options.overwrite && options.dedupeName === undefined)
  21. options.dedupeName = false;
  22. // if targetPath is not provided or it's not starting with a slash, it means it's a relative path
  23. // in that case, we need to prepend the app's root directory to it
  24. targetPath = getAbsolutePathForApp(targetPath);
  25. // extract file name from targetPath
  26. const filename = path.basename(targetPath);
  27. // extract the parent directory from targetPath
  28. const parent = path.dirname(targetPath);
  29. // if data is a string, convert it to a File object
  30. if(typeof data === 'string'){
  31. data = new File([data ?? ''], filename ?? 'Untitled.txt', { type: "text/plain" });
  32. }
  33. // blob
  34. else if(data instanceof Blob){
  35. data = new File([data ?? ''], filename ?? 'Untitled', { type: data.type });
  36. }
  37. if(!data)
  38. data = new File([data ?? ''], filename);
  39. // perform upload
  40. return this.upload(data, parent, options);
  41. }
  42. export default write;