Repository navigation
Expand file tree
/
Copy pathaddFileList.js
More file actions
74 lines (57 loc) · 1.65 KB
/
Copy pathaddFileList.js
File metadata and controls
74 lines (57 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
Allows files to be added to jsdom input elements.
addFileList(input, file_paths)
Effects: puts the file_paths as File object in input.files as a FileList
Returns: input
Arguments:
input - HTML input element
file_paths
- String of a file path
- Array of strings of file paths
Read File Example:
const input = document.querySelector('input[type=file]')
addFileList(input, 'path/to/file')
const file = input.files[0]
const fr = new FileReader()
fr.readAsText(file)
fr.onload = () => {
console.log('fr.result', fr.result)
console.log('fr.result.length', fr.result.length)
}
Unresolved jsdom issue that references this:
https://github.com/jsdom/jsdom/issues/1272
*/
const fs = require('fs')
const path = require('path')
const mime = require('mime-types')
const { JSDOM } = require('jsdom')
const { File, FileList } = (new JSDOM()).window
function addFileList(input, file_paths) {
if (typeof file_paths === 'string')
file_paths = [file_paths]
else if (!Array.isArray(file_paths)) {
throw new Error('file_paths needs to be a file path string or an Array of file path strings')
}
const file_list = file_paths.map(fp => createFile(fp))
file_list.__proto__ = Object.create(FileList.prototype)
Object.defineProperty(input, 'files', {
value: file_list,
writable: false,
})
return input
}
function createFile(file_path) {
const { mtimeMs: lastModified } = fs.statSync(file_path)
return new File(
[new fs.readFileSync(file_path)],
path.basename(file_path),
{
lastModified,
type: mime.lookup(file_path) || '',
}
)
}
module.exports = {
addFileList,
createFile,
}