-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathutil.js
More file actions
299 lines (252 loc) · 8.05 KB
/
Copy pathutil.js
File metadata and controls
299 lines (252 loc) · 8.05 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
const http = require('http');
const qs = require('querystring');
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const LANG_C = 1;
const LANG_JAVA = 2;
const LANG_CPP = 3;
const LANG_PASCAL = 4;
(function(obj){
obj.LANG_C = LANG_C;
obj.LANG_JAVA = LANG_JAVA;
obj.LANG_CPP = LANG_CPP;
obj.LANG_PASCAL = LANG_PASCAL;
/**
* @param fileExt Lowercase file extension without the dot.
* @return LANG_* constant or -1 if unrecognized
*/
obj.getLang = function(fileExt){
switch (fileExt)
{
case 'c': return LANG_C;
case 'java': return LANG_JAVA;
case 'cc':
case 'cpp': return LANG_CPP;
case 'p':
case 'pascal':
case 'pas': return LANG_PASCAL;
}
return -1;
};
obj.getLangName = function(lang){
lang = parseInt(lang);
switch(lang)
{
case LANG_C: return 'C';
case LANG_JAVA: return 'Java';
case LANG_CPP: return 'C++';
case LANG_PASCAL: return 'Pascal';
}
return '?';
};
/**
* @return File extension without the dot; empty string if none.
*/
obj.getFileExt = function(filePath){
var fileExt = path.extname(filePath);
if (fileExt)
return fileExt.substring(1);
return '';
};
obj.createEndCallback = function(callback){
var buf = '';
return function(inMsg){
inMsg.setEncoding('utf8');
inMsg.on('readable', function(){buf += inMsg.read() || '';})
.on('end', function(){callback(buf, inMsg);});
};
};
/**
* Removes surrounding quote chars (" or ') from a string.
* Any whitespace surrounded by the quote chars are preserved but
* whitespaces outside of the quote chars are removed. If no quote chars
* are present the entire string is trimmed of whitespaces.
* The string is processed adhering to the following rules:
* - the starting and ending quote chars must be the same.
* - if the starting or ending quote char is present, the other must also
* be present, that is, there must be no unmatched quote char.
* <pre>
* Examples:
* String s = " ' hello ' "; // unquote(s) returns "' hello '"
* String s = " 'hello "; // unquote(s) will throw an exception
* String s = " hello "; // unquote(s) returns "hello"
* </pre>
* @param s
* @exception if at least one
* of the rules is violated.
*/
obj.unquote = function(s){
s = s.trim();
if (s.length >= 1)
{
var start = s.charAt(0);
var end = s.length >= 2 ? s.charAt(s.length-1) : 0;
var isQuote =
(start === '"' || start === '\'' ||
end === '"' || end === '\'');
if (isQuote)
{
if (start === end)
return s.substring(1, s.length-1);
throw {message: "mismatched quote chars"};
}
}
return s;
};
/**
* Parses an HTML fragment containing attribute pairs without the
* tag name, in to a map.
* This is a forgiving parser that does not adhere strictly to XML rules,
* but well-formed XML are guaranteed to be parsed correctly.
* @param html This must be in the format: attrib1="value" attrib2="value"
* @return Map of attrib-value pairs. The names and values are NOT HTML
* decoded.
*/
obj.parseAttribs = function(html){
const ATTRIB_PATTERN =
// group 1: attrib name (allowing namespace)
// group 2: value including quote chars if any
/([\w:]+)\s*=\s*("[^"]*"|'[^']*'|\S*)/gi;
var match, pairs = {};
while (match = ATTRIB_PATTERN.exec(html))
{
pairs[match[1]] = obj.unquote(match[2]);
}
return pairs;
};
obj.getUserHomePath = function () {
var p = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
if (p) return p;
throw {message: "Cannot determine user home dir"};
};
obj.htmlDecodeSimple = function(s){
return s.replace(/'/g, '\'')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/&/g, '&');
};
/**
* @param method GET or POST
* @param host domain name
* @param path Absolute path e.g. /index.html
* @param callback response callback function
*/
obj.createReq = function(method, host, path, callback){
var options = {
hostname: host,
path: path,
method: method,
// typical headers to disguise our identity
headers: {
'Referer': 'http://'+host+path,
'Accept-Charset': 'utf-8,ISO-8859-1',
// Use chunked so we don't have to send content-length
'Transfer-Encoding': 'chunked',
// no gzip :(
//'Accept-Encoding': 'gzip,deflate',
'Accept-Language': 'en-US,en;q=0.8',
'User-Agent' : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) "+
"AppleWebKit/537.17 (KHTML, like Gecko) "+
"Chrome/24.0.1312.57 Safari/537.17",
"Accept" : "text/html, application/xml, text/xml, */*"
}
};
return http.request(options, callback);
};
obj.writePostData = function(httpReq, data){
var qstr = qs.stringify(data);
httpReq.setHeader('Content-Type',
"application/x-www-form-urlencoded; charset=UTF-8");
httpReq.end(qstr, 'utf8');
};
obj.writeFormData = function(httpReq, data){
var boundBytes = crypto.pseudoRandomBytes(16);
var boundStr = (new Buffer(boundBytes)).toString('hex');
httpReq.setHeader('Content-Type',
'multipart/form-data; boundary='+boundStr);
var bufCap = 1<<16;
var buf = new Buffer(bufCap);
for (var key in data)
{
var val = data[key];
httpReq.write('--'+boundStr, 'ascii');
// file upload?
if (typeof val === 'object' && val.filePath)
{
httpReq.write("\r\nContent-Disposition: form-data; name=\""+ key +
"\"; filename=\""+val.filePath+"\"\r\n"+
"Content-Type: application/octet-stream\r\n"+
"Content-Transfer-Encoding: binary\r\n\r\n", "utf8");
var fd = fs.openSync(val.filePath, 'r');
var bufSize = 0;
while(true)
{
// read til buffer is full
while (bufSize < bufCap)
{
var nread = fs.readSync(fd, buf, bufSize, bufCap-bufSize, null);
if (nread == 0) break;
bufSize += nread;
}
if (bufSize === bufCap)
{
bufSize = 0;
httpReq.write(buf);
continue;
}
httpReq.write(buf.slice(0, bufSize));
break;
}
fs.closeSync(fd);
httpReq.write("\r\n", 'ascii');
}
else
{
httpReq.write("\r\nContent-Disposition: form-data; name=\""+ key +"\"\r\n\r\n", 'utf8');
httpReq.write(val+"\r\n", 'utf8');
}
}
httpReq.end('--'+boundStr+"--\r\n",'ascii');
};
/**
* Gets a semi-colon-separated list of cookies from the Set-Cookie headers,
* without the cookies' metadata such as expiry and path.
* The cookie keys and values are not decoded.
* @return null if the cookies are not found.
*/
obj.getCookies = function(inMsg){
var cookies = inMsg.headers["set-cookie"];
if (typeof cookies === 'string')
{
cookies = [cookies];
}
else if (!cookies)
return null;
function get(line)
{
var tokens = line.split(';');
// Cookie should be the first token
if (tokens.length >= 1)
{
var pair = tokens[0].split("=");
if (pair.length != 2) return null;
var key = pair[0].trim();
var value = pair[1].trim();
return {key: key, value: value};
}
return null;
}
var z = '';
var sep = '';
for (var i = 0; i < cookies.length; i++)
{
var cookie = get(cookies[i]);
if (!cookie) continue;
z += sep + cookie.key + '=' + cookie.value;
sep = '; ';
}
return z;
};
})(module.exports);