fileUtils.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.canAccessFile = canAccessFile;
  6. exports.copyFileAndMakeWritable = copyFileAndMakeWritable;
  7. exports.fileUploadSizeLimit = exports.existsAsync = void 0;
  8. exports.mkdirIfNeeded = mkdirIfNeeded;
  9. exports.removeFolders = removeFolders;
  10. exports.sanitizeForFilePath = sanitizeForFilePath;
  11. var _fs = _interopRequireDefault(require("fs"));
  12. var _path = _interopRequireDefault(require("path"));
  13. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  14. /**
  15. * Copyright (c) Microsoft Corporation.
  16. *
  17. * Licensed under the Apache License, Version 2.0 (the "License");
  18. * you may not use this file except in compliance with the License.
  19. * You may obtain a copy of the License at
  20. *
  21. * http://www.apache.org/licenses/LICENSE-2.0
  22. *
  23. * Unless required by applicable law or agreed to in writing, software
  24. * distributed under the License is distributed on an "AS IS" BASIS,
  25. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26. * See the License for the specific language governing permissions and
  27. * limitations under the License.
  28. */
  29. const fileUploadSizeLimit = exports.fileUploadSizeLimit = 50 * 1024 * 1024;
  30. const existsAsync = path => new Promise(resolve => _fs.default.stat(path, err => resolve(!err)));
  31. exports.existsAsync = existsAsync;
  32. async function mkdirIfNeeded(filePath) {
  33. // This will harmlessly throw on windows if the dirname is the root directory.
  34. await _fs.default.promises.mkdir(_path.default.dirname(filePath), {
  35. recursive: true
  36. }).catch(() => {});
  37. }
  38. async function removeFolders(dirs) {
  39. return await Promise.all(dirs.map(dir => _fs.default.promises.rm(dir, {
  40. recursive: true,
  41. force: true,
  42. maxRetries: 10
  43. }).catch(e => e)));
  44. }
  45. function canAccessFile(file) {
  46. if (!file) return false;
  47. try {
  48. _fs.default.accessSync(file);
  49. return true;
  50. } catch (e) {
  51. return false;
  52. }
  53. }
  54. async function copyFileAndMakeWritable(from, to) {
  55. await _fs.default.promises.copyFile(from, to);
  56. await _fs.default.promises.chmod(to, 0o664);
  57. }
  58. function sanitizeForFilePath(s) {
  59. return s.replace(/[\x00-\x2C\x2E-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+/g, '-');
  60. }