How to use filePath method in Playwright Internal

Best JavaScript code snippet using playwright-internal

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

exiftool-child.js

Source: exiftool-child.js Github

copy
1const path = require('path');
2const fs = require('fs-extra');
3const prettyBytes = require('pretty-bytes');
4const { readPsd } = require('ag-psd');
5
6const name = 'exiftool-child';
7const log = require('../../lib/log.js')(name);
8const timing = require('../../lib/timing.js')(name);
9const dcrawBin = require('./dcraw-bin.js');
10const { bufferToUrl, urlToBuffer } = require('./bufferToUrl.js');
11const metacache = require('./cache-meta.js');
12const imagecache = require('./cache-image.js');
13const { unknown } = require('./svg.js');
14
15const image = require('../../lib/image.js');
16const exiftool = require('../../lib/exiftool.js');
17const gprtools = require('../../lib/gprtools.js');
18const libheif = require('./libheif.js')(1);
19
20const ROTATION = {
21  'Horizontal (normal)': 0,
22  'Rotate 90 CW': 90,
23  'Rotate 270 CW': 270
24};
25
26function extension(filepath) {
27  return path.extname(filepath).replace(/^\./, '').toLowerCase();
28}
29
30function isPlainImage(filepath) {
31  const ext = path.extname(filepath).toLowerCase();
32  return ['.jpeg', '.jpg', '.png'].includes(ext);
33}
34
35// this can be displayed nativly in Electron, but it is
36// a bit difficult to test, so convert it for now
37function isPlainConvertable(filepath) {
38  const ext = path.extname(filepath).toLowerCase();
39  return ['.webp'].includes(ext);
40}
41
42function isGpr(filepath) {
43  return path.extname(filepath).toLowerCase() === '.gpr';
44}
45
46async function readFullMeta(filepath) {
47  const name = 'fullmeta';
48  const existing = metacache.read(filepath, name);
49
50  if (existing) {
51    return existing;
52  }
53
54  const result = await timing({
55    category: 'read-full-meta-child',
56    variable: extension(filepath),
57    func: async () => await exiftool.readFullMeta(filepath)
58  });
59  metacache.add(filepath, name, result);
60
61  return result;
62}
63
64async function queryMeta(filepath, keys) {
65  return await exiftool.queryMeta(filepath, keys);
66}
67
68async function readShortMeta(filepath) {
69  const name = 'shortmeta';
70  const existing = metacache.read(filepath, name);
71
72  if (existing) {
73    return existing;
74  }
75
76  const placeholder = {
77    disabled: true,
78    url: unknown,
79    rotation: 0,
80    rating: 0,
81    filepath
82  };
83
84  const stat = await fs.stat(filepath);
85
86  if (stat.isDirectory()) {
87    return placeholder;
88  }
89
90  let value;
91  try {
92    value = await timing({
93      label: `read short meta ${filepath}`,
94      category: 'read-short-meta-child',
95      variable: extension(filepath),
96      func: async () => await exiftool.readShortMeta(filepath)
97    });
98  } catch (e) {
99    return placeholder;
100  }
101
102  const result = Object.assign(value, {
103    filepath,
104    rotation: value.isHeic ? 0 : ROTATION[value.orientation] || 0
105  });
106
107  metacache.add(filepath, name, result);
108
109  return result;
110}
111
112async function readFilePart({ filepath, start, length }) {
113  return timing({
114    label: `read file part ${filepath}`,
115    func: async () => {
116      let buffer = Buffer.alloc(length);
117      const fd = await fs.open(filepath, 'r');
118      await fs.read(fd, buffer, 0, length, start);
119      await fs.close(fd);
120
121      return buffer;
122    }
123  });
124}
125
126async function readFile(filepath) {
127  return await timing({
128    label: `read file ${filepath}`,
129    func: () => fs.readFile(filepath)
130  });
131}
132
133async function readFilePsd(filepath) {
134  return await imagecache.cacheable(filepath, 'psd-render', async () => {
135    return await timing({
136      label: `read psd ${filepath}`,
137      func: async () => {
138        const file = await timing({ label: 'psd read', func: () => fs.readFile(filepath) });
139        const psd = await timing({
140          label: 'psd parse',
141          func: () => readPsd(file, {
142            skipLayerImageData: true
143          })
144        });
145        const canvas = psd.canvas;
146        const imgUrl = await timing({ label: 'psd canvas', func: () => canvas.toDataURL('image/jpeg') });
147        const buffer = await timing({ label: 'psd buffer', func: () => urlToBuffer(imgUrl) });
148
149        return buffer;
150      }
151    });
152  });
153}
154
155async function readGpr(filepath) {
156  return await imagecache.cacheable(filepath, 'gpr-render', async () => {
157    return await timing({
158      label: `read gpr ${filepath}`,
159      func: () => gprtools.jpg(filepath)
160    });
161  });
162}
163
164async function readFileHeic(filepath) {
165  return await imagecache.cacheable(filepath, 'heif-render', async () => {
166    return await timing({
167      label: `read heif ${filepath}`,
168      func: () => libheif.jpg(filepath)
169    });
170  });
171}
172
173async function resizeLargeJpeg({ filepath, buffer, length }) {
174  const before = buffer.length;
175
176  buffer = await timing({
177    label: `resize large jpeg for ${filepath}`,
178    func: async () => {
179      const { size: filebytes } = await fs.stat(filepath);
180
181      if (filebytes / 2 < length) {
182        // this jpeg was more than twice the size of the original
183        // raw file... something is off, so resize it... it's too big
184        return await image.bufferToJpeg(buffer);
185      }
186
187      return buffer;
188    }
189  });
190
191  const diff = before - buffer.length;
192  const pretty = prettyBytes(diff * -1);
193  const percent = (1 - (buffer.length / before)) * 100;
194
195  log.info(`change in ${filepath} size: ${pretty}, ${percent.toFixed(1)}%`);
196
197  return buffer;
198}
199
200async function readJpegBufferFromMeta({ filepath, start, length }) {
201  if (start && length) {
202    // we can get a fast jpeg image
203    return await timing({
204      label: `read preview ${filepath}`,
205      func: async () => await readFilePart({ filepath, start, length })
206    });
207  }
208
209  return await timing({
210    label: `dcraw extract preview ${filepath}`,
211    func: async () => {
212      return await dcrawBin(filepath, { type: 'preview' });
213    }
214  });
215}
216
217async function readJpegFromMeta({ filepath, start, length, url, isPsd, isHeic, rotation }) {
218  if (url) {
219    return url;
220  }
221
222  return await timing({
223    label: `read jpeg from meta ${filepath}`,
224    category: 'read-jpeg-from-meta',
225    variable: extension(filepath),
226    func: async () => {
227      let buffer;
228
229      if (isPsd) {
230        buffer = await readFilePsd(filepath);
231      } else if (isHeic) {
232        buffer = await readFileHeic(filepath);
233      } else if (isPlainImage(filepath)) {
234        buffer = await readFile(filepath);
235      } else if (isPlainConvertable(filepath)) {
236        buffer = await image.pathToJpeg(filepath);
237      } else if (isGpr(filepath)) {
238        buffer = await readGpr(filepath);
239      } else {
240        buffer = await readJpegBufferFromMeta({ filepath, start, length });
241      }
242
243      if (length && length > 9999999) {
244        // this image is probably too big, something suspicious is happening
245        // ... it's probably a CR3 file, but I've seen it happen for other
246        // formats as well
247        buffer = await resizeLargeJpeg({ filepath, buffer, length });
248      }
249
250      if (rotation) {
251        buffer = await image.resizeJpeg(buffer, { rotation });
252      }
253
254      return bufferToUrl(buffer);
255    }
256  });
257}
258
259async function readThumbFromMeta(data) {
260  if (data.url) {
261    return data.url;
262  }
263
264  let buffer;
265
266  await timing({
267    category: 'read-thumb-from-meta',
268    variable: extension(data.filepath),
269    func: async () => {
270      if (data.isPsd) {
271        buffer = await readFilePsd(data.filepath);
272      } else if (data.isHeic) {
273        buffer = await readFileHeic(data.filepath);
274      } else if (isPlainImage(data.filepath)) {
275        buffer = await readFile(data.filepath);
276      } else if (isPlainConvertable(data.filepath)) {
277        buffer = await image.pathToJpeg(data.filepath);
278      } else if (isGpr(data.filepath)) {
279        buffer = await readGpr(data.filepath);
280      } else if (data.thumbStart && data.thumbLength) {
281        // sometimes, the raw file will store a full size preview
282        // and a thumbnail, and in those cases, using the smaller
283        // image will be faster... though the resize makes large
284        // images pretty fast, so maybe it's not worth?
285        buffer = await timing({
286          label: `read thumb ${data.filepath}`,
287          func: async () => await readFilePart({
288            filepath: data.filepath,
289            start: data.thumbStart,
290            length: data.thumbLength
291          })
292        });
293      } else {
294        buffer = await readJpegBufferFromMeta(data);
295      }
296    }
297  });
298
299  buffer = await timing({
300    label: `resize thumb ${data.filepath}`,
301    category: 'resize-thumbnail',
302    variable: extension(data.filepath),
303    func: async () => await image.resizeJpeg(buffer, { width: 200, rotation: data.rotation })
304  });
305
306  return bufferToUrl(buffer);
307}
308
309async function setRating(filepath, rating = 0) {
310  metacache.remove(filepath);
311  return await exiftool.setRating(filepath, rating);
312}
313
314async function copyMeta(filepath, targetpath) {
315  return await exiftool.copyMeta(filepath, targetpath);
316}
317
318async function rawRender(filepath) {
319  return imagecache.cacheable(filepath, 'raw', async () => {
320    return await timing({
321      label: `render ${filepath} from RAW`,
322      category: 'raw-render',
323      variable: extension(filepath),
324      func: async () => {
325        const jpeg = await dcrawBin(filepath, { type: 'raw' });
326        return bufferToUrl(jpeg);
327      }
328    });
329  });
330}
331
332module.exports = {
333  readFullMeta,
334  readShortMeta,
335  queryMeta,
336  copyMeta,
337  setRating,
338  readJpegFromMeta,
339  readThumbFromMeta,
340  isPlainImage,
341  rawRender,
342  resetCache: () => metacache.reset()
343};
344
Full Screen

sb-watch.js

Source: sb-watch.js Github

copy
1'use strict';
2
3const _ = require('lodash');
4const chokidar = require('chokidar');
5const path = require('path');
6const renderAssets = require('./render-assets');
7const renderPug = require('./render-pug');
8const renderScripts = require('./render-scripts');
9const renderSCSS = require('./render-scss');
10
11const watcher = chokidar.watch('src', {
12    persistent: true,
13});
14
15let READY = false;
16
17process.title = 'pug-watch';
18process.stdout.write('Loading');
19let allPugFiles = {};
20
21watcher.on('add', filePath => _processFile(filePath, 'add'));
22watcher.on('change', filePath => _processFile(filePath, 'change'));
23watcher.on('ready', () => {
24    READY = true;
25    console.log(' READY TO ROLL!');
26});
27
28_handleSCSS();
29
30function _processFile(filePath, watchEvent) {
31    
32    if (!READY) {
33        if (filePath.match(/\.pug$/)) {
34            if (!filePath.match(/includes/) && !filePath.match(/mixins/) && !filePath.match(/\/pug\/layouts\//)) {
35                allPugFiles[filePath] = true;
36            }    
37        }    
38        process.stdout.write('.');
39        return;
40    }
41
42    console.log(`### INFO: File event: ${watchEvent}: ${filePath}`);
43
44    if (filePath.match(/\.pug$/)) {
45        return _handlePug(filePath, watchEvent);
46    }
47
48    if (filePath.match(/\.scss$/)) {
49        if (watchEvent === 'change') {
50            return _handleSCSS(filePath, watchEvent);
51        }
52        return;
53    }
54
55    if (filePath.match(/src\/js\//)) {
56        return renderScripts();
57    }
58
59    if (filePath.match(/src\/assets\//)) {
60        return renderAssets();
61    }
62
63}
64
65function _handlePug(filePath, watchEvent) {
66    if (watchEvent === 'change') {
67        if (filePath.match(/includes/) || filePath.match(/mixins/) || filePath.match(/\/pug\/layouts\//)) {
68            return _renderAllPug();
69        }
70        return renderPug(filePath);
71    }
72    if (!filePath.match(/includes/) && !filePath.match(/mixins/) && !filePath.match(/\/pug\/layouts\//)) {
73        return renderPug(filePath);
74    }
75}
76
77function _renderAllPug() {
78    console.log('### INFO: Rendering All');
79    _.each(allPugFiles, (value, filePath) => {
80        renderPug(filePath);
81    });
82}
83
84function _handleSCSS() {
85    renderSCSS();
86}
Full Screen

index.js

Source: index.js Github

copy
1/*!
2 * detect-file <https://github.com/doowb/detect-file>
3 *
4 * Copyright (c) 2016-2017, Brian Woodward.
5 * Released under the MIT License.
6 */
7
8'use strict';
9
10var fs = require('fs');
11var path = require('path');
12
13/**
14 * Detect the given `filepath` if it exists.
15 *
16 * ```js
17 * var res = detect('package.json');
18 * console.log(res);
19 * //=> "package.json"
20 *
21 * var res = detect('fake-file.json');
22 * console.log(res)
23 * //=> null
24 * ```
25 *
26 * @param  {String} `filepath` filepath to detect.
27 * @param  {Object} `options` Additional options.
28 * @param  {Boolean} `options.nocase` Set this to `true` to force case-insensitive filename checks. This is useful on case sensitive file systems.
29 * @return {String} Returns the detected filepath if it exists, otherwise returns `null`.
30 * @api public
31 */
32
33module.exports = function detect(filepath, options) {
34  if (!filepath || (typeof filepath !== 'string')) {
35    return null;
36  }
37  if (fs.existsSync(filepath)) {
38    return path.resolve(filepath);
39  }
40
41  options = options || {};
42  if (options.nocase === true) {
43    return nocase(filepath);
44  }
45  return null;
46};
47
48/**
49 * Check if the filepath exists by falling back to reading in the entire directory.
50 * Returns the real filepath (for case sensitive file systems) if found.
51 *
52 * @param  {String} `filepath` filepath to check.
53 * @return {String} Returns found filepath if exists, otherwise null.
54 */
55
56function nocase(filepath) {
57  filepath = path.resolve(filepath);
58  var res = tryReaddir(filepath);
59  if (res === null) {
60    return null;
61  }
62
63  // "filepath" is a directory, an error would be
64  // thrown if it doesn't exist. if we're here, it exists
65  if (res.path === filepath) {
66    return res.path;
67  }
68
69  // "filepath" is not a directory
70  // compare against upper case later
71  // see https://nodejs.org/en/docs/guides/working-with-different-filesystems/
72  var upper = filepath.toUpperCase();
73  var len = res.files.length;
74  var idx = -1;
75
76  while (++idx < len) {
77    var fp = path.resolve(res.path, res.files[idx]);
78    if (filepath === fp || upper === fp) {
79      return fp;
80    }
81    var fpUpper = fp.toUpperCase();
82    if (filepath === fpUpper || upper === fpUpper) {
83      return fp;
84    }
85  }
86
87  return null;
88}
89
90/**
91 * Try to read the filepath as a directory first, then fallback to the filepath's dirname.
92 *
93 * @param  {String} `filepath` path of the directory to read.
94 * @return {Object} Object containing `path` and `files` if succesful. Otherwise, null.
95 */
96
97function tryReaddir(filepath) {
98  var ctx = { path: filepath, files: [] };
99  try {
100    ctx.files = fs.readdirSync(filepath);
101    return ctx;
102  } catch (err) {}
103  try {
104    ctx.path = path.dirname(filepath);
105    ctx.files = fs.readdirSync(ctx.path);
106    return ctx;
107  } catch (err) {}
108  return null;
109}
110
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Internal on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)