1 | const URL = require('url')
|
2 | const queryParser = require('querystring')
|
3 | const _memoryFileMap = {}
|
4 | const { util, crypto } = require('./util')
|
5 |
|
6 | class MemoryFile {
|
7 | static get (name) {
|
8 | if (_memoryFileMap[name]) {
|
9 | return _memoryFileMap[name]
|
10 | }
|
11 | else {
|
12 | const keys = _memoryFileMap
|
13 | let content
|
14 | for (let key in keys) {
|
15 | if (key.indexOf(name) >= 0) {
|
16 | content = _memoryFileMap[key]
|
17 | break
|
18 | }
|
19 | }
|
20 | return content
|
21 | }
|
22 | }
|
23 | static dump () {
|
24 | return Object.keys(_memoryFileMap)
|
25 | }
|
26 | constructor (fileName, content) {
|
27 | const rHttpHeader = /^(https?|taobao|qap):\/\/(?!.*your_current_ip)/i
|
28 | if (rHttpHeader.test(fileName)) {
|
29 | const query = queryParser.parse(URL.parse(fileName).query)
|
30 | if (query['_wx_tpl']) {
|
31 | this.url = util.normalize(query['_wx_tpl'])
|
32 | this.name = this.url.replace(rHttpHeader, '')
|
33 | }
|
34 | else {
|
35 | this.url = util.normalize(fileName)
|
36 | this.name = this.url.replace(rHttpHeader, '')
|
37 | }
|
38 | }
|
39 | else {
|
40 | this.name = fileName.replace(
|
41 | /^(https?|taobao|qap):\/\/(.*your_current_ip):(\d+)\
|
42 | 'file://'
|
43 | )
|
44 | }
|
45 | if (this.name.charAt(this.name.length - 1) === '?') {
|
46 | this.name = this.name.substring(0, this.name.length - 1)
|
47 | }
|
48 | const md5Str = crypto.md5(content + fileName)
|
49 | const key = this.name.split('?')[0] + '|' + md5Str
|
50 | if (_memoryFileMap[this.name]) {
|
51 | _memoryFileMap[this.name].content = content
|
52 | return _memoryFileMap[this.name]
|
53 | }
|
54 | else if (_memoryFileMap[key]) {
|
55 | _memoryFileMap[key].content = content
|
56 | return _memoryFileMap[key]
|
57 | }
|
58 | else {
|
59 | this.content = content
|
60 | }
|
61 | this.md5 = md5Str
|
62 | _memoryFileMap[this.name] = this
|
63 | _memoryFileMap[key] = this
|
64 | }
|
65 | getContent () {
|
66 | return this.content
|
67 | }
|
68 | getUrl () {
|
69 | return '/source/' + this.name
|
70 | }
|
71 | }
|
72 | module.exports = MemoryFile
|