├── LICENSE ├── README.md ├── main.js ├── package.json ├── rfc822.js └── test ├── index.html ├── server.js └── test.js /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # filed -- Simplified file library. 2 | 3 | ## Install 4 | 5 |
 6 |   npm install filed
 7 | 
8 | 9 | ## Super simple to use 10 | 11 | Filed does a lazy stat call so you can actually open a file and begin writing to it and if the file isn't there it will just be created. 12 | 13 | ```javascript 14 | var filed = require('filed'); 15 | var f = filed('/newfile') 16 | f.write('test') 17 | f.end() 18 | ``` 19 | 20 | ## Streaming 21 | 22 | The returned file object is a stream so you can do standard stream stuff to it. Based on *what* you do the object it will be a read stream, a write stream. 23 | 24 | So if you send data to it, it'll be a write stream. 25 | 26 | ```javascript 27 | fs.createReadStream.pipe(filed('/newfile')) 28 | ``` 29 | 30 | If you pipe it to a destination it'll be a read stream. 31 | 32 | ```javascript 33 | filed('/myfile').pipe(fs.createWriteStream('/out')) 34 | ``` 35 | 36 | And of course you can pipe a filed object from itself to itself and it'll figure it out. 37 | 38 | ```javascript 39 | filed('/myfile').pipe(filed('/newfile')) 40 | ``` 41 | 42 | Those familiar with [request](http://github.com/mikeal/request) will be familiar seeing object capability detection when doing HTTP. filed does this as well. 43 | 44 | ```javascript 45 | http.createServer(function (req, resp) { 46 | filed('/data.json').pipe(resp) 47 | }) 48 | ``` 49 | 50 | Not only does the JSON file get streamed to the HTTP Response it will include an Etag, Last-Modified, Content-Length, and a Content-Type header based on the filed extension. 51 | 52 | ```javascript 53 | http.createServer(function (req, resp) { 54 | req.pipe(filed('/newfile')).pipe(resp) 55 | }) 56 | ``` 57 | 58 | When accepting a PUT request data will be streamed to the file and a 201 status will be sent on the HTTP Response when the upload is finished. 59 | 60 | During a GET request a 404 Response will be sent if the file does not exist. 61 | 62 | ```javascript 63 | http.createServer(function (req, resp) { 64 | req.pipe(filed('/data.json')).pipe(resp) 65 | }) 66 | ``` 67 | 68 | The Etag and Last-Modified headers filed creates are based solely on the stat() call so if you pipe a request to an existing file the cache control headers will be taken into account; a 304 response will be sent if the cache control headers match a new stat() call. This can be very helpful in avoiding unnecessary disc reads. 69 | 70 | ```javascript 71 | http.createServer(function (req, resp) { 72 | req.pipe(filed('/directory')).pipe(resp) 73 | }) 74 | ``` 75 | 76 | Just to round out the full feature set and make it full file server if you give filed an existing directory it will actually check for an index.html file in that directory and serve it if it exists. 77 | 78 | ## License 79 | `ASL 2.0`, see [LICENSE](LICENSE) file. 80 | -------------------------------------------------------------------------------- /main.js: -------------------------------------------------------------------------------- 1 | var fs = require('fs') 2 | , util = require('util') 3 | , crypto = require('crypto') 4 | , stream = require('stream') 5 | , path = require('path') 6 | , mime = require('mime') 7 | , rfc822 = require('./rfc822') 8 | ; 9 | 10 | function File (options) { 11 | stream.Stream.call(this) 12 | 13 | this.writable = true 14 | this.readable = true 15 | this.buffers = [] 16 | 17 | var self = this 18 | 19 | if (typeof options === 'string') options = {path:options} 20 | if (!options.index) options.index = 'index.html' 21 | self.writable = (typeof options.writable === "undefined") ? true : options.writable 22 | self.readable = (typeof options.readable === "undefined") ? true : options.readable 23 | 24 | self.path = options.path 25 | self.index = options.index 26 | 27 | self.on('pipe', function (src) { 28 | this.src = src 29 | }) 30 | 31 | this.buffering = true 32 | 33 | this.mimetype = options.mimetype || mime.getType(this.path.slice(this.path.lastIndexOf('.')+1)) 34 | 35 | var stopBuffering = function () { 36 | self.buffering = false 37 | while (self.buffers.length) { 38 | self.emit('data', self.buffers.shift()) 39 | } 40 | if (self.ended) self.emit('end') 41 | } 42 | 43 | fs.stat(options.path, function (err, stats) { 44 | 45 | var finish = function (err, stats) { 46 | self.stat = stats 47 | if (err && err.code === 'ENOENT' && !self.dest && !self.src) self.src = self.path 48 | if (err && !self.dest && !self.src) return self.emit('error', err) 49 | if (err && self.dest && !self.dest.writeHead) return self.emit('error', err) 50 | 51 | // See if writes are disabled 52 | if (self.src && self.src.method && 53 | !self.writable && self.dest.writeHead && 54 | (self.src.method === 'PUT' || self.src.method === 'POST')) { 55 | self.dest.writeHead(405, {'content-type':'text/plain'}) 56 | self.dest.end(self.src.method+' Not Allowed') 57 | return 58 | } 59 | 60 | if (!err) { 61 | self.etag = crypto.createHash('md5').update(stats.ino+'/'+stats.mtime+'/'+stats.size).digest("hex") 62 | self.lastmodified = rfc822.getRFC822Date(stats.mtime) 63 | } 64 | 65 | process.nextTick(function () { 66 | stopBuffering() 67 | }) 68 | 69 | // 404 and 500 70 | if ( err && self.dest && self.dest.writeHead && // We have an error object and dest is an HTTP response 71 | ( // Either we have a source and it's a GET/HEAD or we don't have a src 72 | (self.src && (self.src.method == 'GET' || self.src.method === 'HEAD')) || (!self.src) 73 | ) 74 | ) { 75 | if (err.code === 'ENOENT') { 76 | self.dest.statusCode = 404 77 | self.dest.end('Not Found') 78 | } else { 79 | self.dest.statusCode = 500 80 | self.dest.end(err.message) 81 | } 82 | return 83 | } 84 | 85 | // Source is an HTTP Server Request 86 | if (self.src && (self.src.method === 'GET' || self.src.method === 'HEAD') && self.dest) { 87 | if (self.dest.setHeader) { 88 | self.dest.setHeader('content-type', self.mimetype) 89 | self.dest.setHeader('etag', self.etag) 90 | self.dest.setHeader('last-modified', self.lastmodified) 91 | } 92 | 93 | if (self.dest.writeHead) { 94 | if (self.src && self.src.headers) { 95 | if (self.src.headers['if-none-match'] === self.etag || 96 | // Lazy last-modifed matching but it's faster than parsing Datetime 97 | self.src.headers['if-modified-since'] === self.lastmodified) { 98 | self.dest.statusCode = 304 99 | self.dest.end() 100 | return 101 | } 102 | } 103 | // We're going to return the whole file 104 | self.dest.statusCode = 200 105 | self.dest.setHeader('content-length', stats.size) 106 | } else { 107 | // Destination is not an HTTP response, GET and HEAD method are not allowed 108 | return 109 | } 110 | 111 | if (self.src.method !== 'HEAD') { 112 | fs.createReadStream(self.path).pipe(self.dest) 113 | } 114 | return 115 | } 116 | 117 | if (self.src && (self.src.method === 'PUT' || self.src.method === 'POST')) { 118 | if (!err) { 119 | // TODO handle overwrite case 120 | return 121 | } 122 | stream.Stream.prototype.pipe.call(self, fs.createWriteStream(self.path)) 123 | if (self.dest && self.dest.writeHead) { 124 | self.on('end', function () { 125 | self.dest.statusCode = 201 126 | self.dest.setHeader('content-length', 0) 127 | self.dest.end() 128 | }) 129 | } 130 | return 131 | } 132 | 133 | // Desination is an HTTP response, we already handled 404 and 500 134 | if (self.dest && self.dest.writeHead) { 135 | self.dest.statusCode = 200 136 | self.dest.setHeader('content-type', self.mimetype) 137 | self.dest.setHeader('etag', self.etag) 138 | self.dest.setHeader('last-modified', self.lastmodified) 139 | self.dest.setHeader('content-length', stats.size) 140 | fs.createReadStream(self.path).pipe(self.dest) 141 | return 142 | } 143 | 144 | // Destination is not an HTTP request 145 | 146 | if (self.src && !self.dest) { 147 | stream.Stream.prototype.pipe.call(self, fs.createWriteStream(self.path)) 148 | } else if (self.dest && !self.src) { 149 | fs.createReadStream(self.path).pipe(self.dest) 150 | } 151 | } 152 | 153 | if (!err && stats.isDirectory()) { 154 | self.path = path.join(self.path, self.index) 155 | self.mimetype = mime.getType(self.path.slice(self.path.lastIndexOf('.')+1)) 156 | fs.stat(self.path, finish) 157 | return 158 | } else { 159 | finish(err, stats) 160 | } 161 | 162 | if (!self.src && !self.dest) { 163 | if (self.buffers.length > 0) { 164 | stream.Stream.prototype.pipe.call(self, fs.createWriteStream(self.path)) 165 | } else if (self.listeners('data').length > 0) { 166 | fs.createReadStream(self.path).pipe(self.dest) 167 | } else { 168 | fs.createReadStream(self.path).pipe(self) 169 | } 170 | } 171 | 172 | }) 173 | 174 | } 175 | util.inherits(File, stream.Stream) 176 | File.prototype.pipe = function (dest, options) { 177 | this.dest = dest 178 | this.destOptions = options 179 | dest.emit('pipe', this) 180 | // stream.Stream.prototype.pipe.call(this, dest, options) 181 | return dest 182 | } 183 | File.prototype.write = function (chunk, encoding) { 184 | if (encoding) chunk = chunk.toString(encoding) 185 | if (this.buffering) { 186 | this.buffers.push(chunk) 187 | } else { 188 | this.emit('data', chunk) 189 | } 190 | } 191 | File.prototype.end = function (chunk) { 192 | if (chunk) this.write(chunk) 193 | if (this.buffering) { 194 | this.ended = true 195 | } else { 196 | this.emit('end') 197 | } 198 | } 199 | 200 | module.exports = function (options) { 201 | return new File(options) 202 | } 203 | module.exports.File = File 204 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "filed", 3 | "description": "Simplified file library.", 4 | "version": "0.2.1", 5 | "repository": { 6 | "type": "git", 7 | "url": "git://github.com/mikeal/filed.git" 8 | }, 9 | "author": "Mikeal Rogers ", 10 | "engines": { 11 | "node": "*" 12 | }, 13 | "license": "ASL 2.0", 14 | "dependencies": { 15 | "mime": "1.2.6" 16 | }, 17 | "scripts": { 18 | "test": "node test/test.js" 19 | }, 20 | "main": "./main" 21 | } 22 | -------------------------------------------------------------------------------- /rfc822.js: -------------------------------------------------------------------------------- 1 | // Support for rfc822, worst standard EVAR! 2 | 3 | // require('./date') 4 | 5 | function getRFC822Date(oDate) 6 | { 7 | var aMonths = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", 8 | "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"); 9 | 10 | var aDays = new Array( "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"); 11 | var dtm = new String(); 12 | 13 | dtm = aDays[oDate.getDay()] + ", "; 14 | dtm += padWithZero(oDate.getDate()) + " "; 15 | dtm += aMonths[oDate.getMonth()] + " "; 16 | dtm += oDate.getFullYear() + " "; 17 | dtm += padWithZero(oDate.getHours()) + ":"; 18 | dtm += padWithZero(oDate.getMinutes()) + ":"; 19 | dtm += padWithZero(oDate.getSeconds()) + " " ; 20 | dtm += getTZOString(oDate.getTimezoneOffset()); 21 | return dtm; 22 | } 23 | //Pads numbers with a preceding 0 if the number is less than 10. 24 | function padWithZero(val) 25 | { 26 | if (parseInt(val) < 10) 27 | { 28 | return "0" + val; 29 | } 30 | return val; 31 | } 32 | 33 | /* accepts the client's time zone offset from GMT in minutes as a parameter. 34 | returns the timezone offset in the format [+|-}DDDD */ 35 | function getTZOString(timezoneOffset) 36 | { 37 | var hours = Math.floor(timezoneOffset/60); 38 | var modMin = Math.abs(timezoneOffset%60); 39 | var s = new String(); 40 | s += (hours > 0) ? "-" : "+"; 41 | var absHours = Math.abs(hours) 42 | s += (absHours < 10) ? "0" + absHours :absHours; 43 | s += ((modMin == 0) ? "00" : modMin); 44 | return(s); 45 | } 46 | 47 | exports.getRFC822Date = getRFC822Date; 48 | -------------------------------------------------------------------------------- /test/index.html: -------------------------------------------------------------------------------- 1 | test -------------------------------------------------------------------------------- /test/server.js: -------------------------------------------------------------------------------- 1 | var http = require('http') 2 | 3 | function createServer () { 4 | var s = http.createServer(function (req, resp) { 5 | resp.___end = resp.end 6 | resp.end = function (chunk) { 7 | s.completed[req.url] = true 8 | resp.___end(chunk) 9 | if (Object.keys(s._events).filter(function(n){return n[0] === '/'}).length === Object.keys(s.completed).length) { 10 | setTimeout(function () { 11 | s.close() 12 | }, 0) 13 | } 14 | } 15 | s.emit(req.url, req, resp) 16 | }) 17 | s.completed = {} 18 | return s; 19 | } 20 | module.exports = createServer; -------------------------------------------------------------------------------- /test/test.js: -------------------------------------------------------------------------------- 1 | var filed = require('../main') 2 | , server = require('./server') 3 | , fs = require('fs') 4 | , path = require('path') 5 | , assert = require('assert') 6 | , request = require('request') 7 | , test1buffer = '' 8 | , testfile = path.join(__dirname, 'test.js') 9 | , writefile = path.join(__dirname, 'testdump-') 10 | , cleanup = [] 11 | , validations = [] 12 | , port = 9090 13 | , i = 0 14 | , url = 'http://localhost:'+port 15 | ; 16 | 17 | while (i < 50) { 18 | try {fs.unlinkSync(writefile+i)} 19 | catch (e) {} 20 | i += 1 21 | } 22 | 23 | function FileValidator (path) { 24 | this.path = path 25 | this.buffers = [] 26 | this.len = 0 27 | this.writable = true 28 | } 29 | FileValidator.prototype.write = function (chunk) { 30 | this.buffers.push(chunk) 31 | this.len += chunk.length 32 | } 33 | FileValidator.prototype.end = function () { 34 | var body = new Buffer(this.len) 35 | var i = 0 36 | this.buffers.forEach(function (chunk) { 37 | chunk.copy(body, i, 0, chunk.length) 38 | i += chunk.length 39 | }) 40 | var f = fs.readFileSync(this.path) 41 | assert.equal(body.length, f.length) 42 | assert.deepEqual(body, f) 43 | } 44 | FileValidator.prototype.on = function () {} 45 | FileValidator.prototype.removeListener = function () {} 46 | FileValidator.prototype.emit = function () {} 47 | 48 | function equalSync (f1, f2) { 49 | f1 = fs.readFileSync(f1) 50 | f2 = fs.readFileSync(f2) 51 | assert.equal(f1.length, f2.length) 52 | assert.deepEqual(f1, f2) 53 | } 54 | 55 | // Test reading 56 | filed(testfile).pipe(new FileValidator(testfile)) 57 | 58 | // Test writing 59 | 60 | function testwrites () { 61 | var x = filed(writefile+1) 62 | , y = fs.createReadStream(testfile) 63 | ; 64 | y.pipe(x) 65 | x.on('end', function () { 66 | setTimeout(function () { 67 | equalSync(writefile+1, testfile) 68 | console.log("Passed writing files") 69 | }, 1000) 70 | }) 71 | } 72 | testwrites() 73 | 74 | function testhttp () { 75 | // Test HTTP use cases 76 | var s = server() 77 | s.on('/test-req', function (req, resp) { 78 | // Take a request and write it, do not send filed to the response 79 | req.pipe(filed(writefile+2)) 80 | req.on('end', function () { 81 | resp.writeHead(201) 82 | resp.end() 83 | setTimeout(function () { 84 | equalSync(writefile+2, testfile) 85 | console.log("Passed PUT file with pipe req only") 86 | }, 1000) 87 | }) 88 | }) 89 | 90 | s.on('/test-req-resp', function (req, resp) { 91 | // Take a request and write it and pipe filed to the response 92 | var x = filed(writefile+3) 93 | req.pipe(x) 94 | x.pipe(resp) 95 | req.on('end', function () { 96 | setTimeout(function () { 97 | equalSync(writefile+3, testfile) 98 | console.log("Passed PUT file with pipe req and resp") 99 | }, 1000) 100 | }) 101 | }) 102 | 103 | s.on('/test-resp', function (req, resp) { 104 | // Send a file to an HTTP response 105 | filed(testfile).pipe(resp) 106 | }) 107 | 108 | var fullpipe = function (req, resp) { 109 | var x = filed(testfile) 110 | req.pipe(x) 111 | x.pipe(resp) 112 | } 113 | 114 | s.on('/test-etags-wo', function (req, resp) { 115 | fullpipe(req, resp) 116 | }) 117 | s.on('/test-etags-with', function (req, resp) { 118 | fullpipe(req, resp) 119 | }) 120 | 121 | s.on('/test-lastmodified-wo', function (req, resp) { 122 | fullpipe(req, resp) 123 | }) 124 | s.on('/test-lastmodified-with', function (req, resp) { 125 | fullpipe(req, resp) 126 | }) 127 | 128 | s.on('/test-index', function (req, resp) { 129 | var x = filed(__dirname) 130 | x.pipe(resp) 131 | }) 132 | 133 | s.on('/test-index-full', function (req, resp) { 134 | var x = filed(__dirname) 135 | req.pipe(x) 136 | x.pipe(resp) 137 | }) 138 | 139 | s.on('/test-not-found', function (req, resp) { 140 | var x = filed(__dirname + "/there-is-no-such-file-here.no-extension") 141 | req.pipe(x) 142 | x.pipe(resp) 143 | }) 144 | 145 | s.listen(port, function () { 146 | 147 | fs.createReadStream(testfile).pipe(request.put(url+'/test-req')) 148 | 149 | fs.createReadStream(testfile).pipe(request.put(url+'/test-req-resp', function (e, resp) { 150 | assert.equal(resp.statusCode, 201) 151 | assert.equal(resp.headers['content-length'], '0') 152 | })) 153 | 154 | var x = request.get(url+'/test-resp', function (e, resp) { 155 | if (e) throw e 156 | assert.equal(resp.statusCode, 200) 157 | assert.equal(resp.headers['content-type'], 'application/javascript') 158 | console.log("Passed GET file without piping request") 159 | }) 160 | x.pipe(new FileValidator(testfile)) 161 | 162 | request.get(url+'/test-etags-wo', function (e, resp, body) { 163 | if (e) throw e 164 | if (resp.statusCode !== 200) throw new Error('Status code is not 200 it is '+resp.statusCode) 165 | request.get({url:url+'/test-etags-with', headers:{'if-none-match':resp.headers.etag}}, function (e, resp) { 166 | if (e) throw e 167 | if (resp.statusCode !== 304) throw new Error('Status code is not 304 it is '+resp.statusCode) 168 | console.log("Passed GET with etag") 169 | }) 170 | }) 171 | 172 | request.get(url+'/test-lastmodified-wo', function (e, resp, body) { 173 | if (e) throw e 174 | if (resp.statusCode !== 200) throw new Error('Status code is not 200 it is '+resp.statusCode) 175 | request.get({url:url+'/test-lastmodified-with', headers:{'if-modified-since':resp.headers['last-modified']}}, function (e, resp) { 176 | if (e) throw e 177 | if (resp.statusCode !== 304) throw new Error('Status code is not 304 it is '+resp.statusCode) 178 | console.log("Passed GET with if-modified-since") 179 | }) 180 | }) 181 | 182 | request.get(url+'/test-index', function (e, resp, body) { 183 | if (e) throw e 184 | if (resp.statusCode !== 200) throw new Error('Status code is not 200 it is '+resp.statusCode) 185 | assert.equal(resp.headers['content-type'], 'text/html') 186 | assert.equal(body, fs.readFileSync(path.join(__dirname, 'index.html')).toString()) 187 | console.log("Passed GET of directory index") 188 | }) 189 | 190 | request.get(url+'/test-index-full', function (e, resp, body) { 191 | if (e) throw e 192 | if (resp.statusCode !== 200) throw new Error('Status code is not 200 it is '+resp.statusCode) 193 | assert.equal(resp.headers['content-type'], 'text/html') 194 | assert.equal(body, fs.readFileSync(path.join(__dirname, 'index.html')).toString()) 195 | console.log("Passed GET of directory index, full pipe") 196 | }) 197 | 198 | request.get(url+'/test-not-found', function (e, resp, body) { 199 | if (e) throw e 200 | if (resp.statusCode !== 404) throw new Error('Status code is not 404 it is '+resp.statusCode) 201 | console.log("Passed Not Found produces 404") 202 | }) 203 | 204 | }) 205 | 206 | } 207 | testhttp() 208 | 209 | process.on('exit', function () {console.log('All tests passed.')}) 210 | --------------------------------------------------------------------------------