├── .gitignore ├── LICENSE ├── README.md ├── gulp-env.d.ts ├── index.js ├── node.d.ts ├── package.json └── test ├── mock-env-ini.ini ├── mock-env-json.json ├── mock-env-json.txt ├── mock-env-module.js ├── mock-env-txt.txt └── test-gulp-env.js /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | 5 | # Runtime data 6 | pids 7 | *.pid 8 | *.seed 9 | 10 | # Directory for instrumented libs generated by jscoverage/JSCover 11 | lib-cov 12 | 13 | # Coverage directory used by tools like istanbul 14 | coverage 15 | 16 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 17 | .grunt 18 | 19 | # Compiled binary addons (http://nodejs.org/api/addons.html) 20 | build/Release 21 | 22 | # Dependency directory 23 | # Commenting this out is preferred by some people, see 24 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- 25 | node_modules 26 | 27 | # Users Environment Variables 28 | .lock-wscript 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Moveline 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | gulp-env 2 | ======== 3 | 4 | Add or modify variables in your `process.env`. 5 | 6 | Purpose 7 | ======== 8 | 9 | Often, two processes running at the same time need different environmental variables (for example: running tests and a server from the same gulp process). `gulp-env` helps simplify that problem, by letting you establish your env vars whenever you'd like, in a simpler interface. You can set values from an external `.json`, `.ini`, or other file, or programmatically set them directly by using `env({vars:{}})` or `env.set(vars)`. 10 | 11 | Install 12 | ======== 13 | 14 | ``` 15 | npm i --save-dev gulp-env 16 | ``` 17 | 18 | The TypeScript definition file is available in gulp-env.d.ts within the base directory. 19 | 20 | Usage 21 | ====== 22 | 23 | ### Example 24 | 25 | Nodemon server: 26 | 27 | ```js 28 | // gulpfile.js 29 | var gulp = require('gulp'); 30 | var nodemon = require('gulp-nodemon'); 31 | var env = require('gulp-env'); 32 | 33 | gulp.task('nodemon', function() { 34 | env({ 35 | file: '.env.json', 36 | vars: { 37 | // any variables you want to overwrite 38 | } 39 | }); 40 | 41 | nodemon({ 42 | script: 'server.js', 43 | ext: 'js html' 44 | // other config ... 45 | }); 46 | }); 47 | 48 | gulp.task('default', ['nodemon']); 49 | ``` 50 | 51 | ES6 web development: 52 | 53 | ```js 54 | import gulp from 'gulp'; 55 | import browserify from 'browserify'; 56 | import transform from 'vinyl-transform'; 57 | import babel from 'gulp-babel'; 58 | import concat from 'gulp-concat'; 59 | import jshint from 'gulp-jshint'; 60 | import uglify from 'gulp-uglify'; 61 | import sourcemaps from 'gulp-sourcemaps'; 62 | 63 | gulp.task('debug', () => { 64 | const envs = env.set({ 65 | NODE_ENV: 'debug' 66 | }); 67 | return gulp.src('src/main.js') 68 | .pipe(envs) 69 | .pipe(babel({optional: [ 70 | 'utility.inlineEnvironmentVariables' 71 | ]})) 72 | .pipe(uglify()) 73 | .pipe(transform(file => browserify(file).bundle())) 74 | .pipe(envs.reset) 75 | .pipe(gulp.dest('dist')); 76 | }); 77 | ``` 78 | 79 | Simple CoffeeScript library's gulpfile: 80 | 81 | ```coffee 82 | gulp = require 'gulp' 83 | coffee = require 'gulp-coffee' 84 | mocha = require 'gulp-mocha' 85 | env = require 'gulp-env' 86 | CSON = require 'cson-safe' 87 | 88 | gulp.task 'compile', -> 89 | gulp.src('src') 90 | .pipe coffee() 91 | .pipe gulp.dest('dest') 92 | 93 | gulp.task 'test', ['compile'], -> 94 | gulp.src('test') 95 | .pipe envs = env 96 | file: 'config.cson' 97 | handler: CSON.parse 98 | .pipe mocha() 99 | .pipe envs.reset 100 | ``` 101 | 102 | ## Details 103 | 104 | `gulp-env` has full test coverage for JSON files, JS modules, INI files, and custom handlers. The entire API below is covered as well. It can also be used in the middle of a Gulp pipeline, where this returns a no-op stream. Note that the `process.env` changes happen synchronously, at the time when the function is called. 105 | 106 | Read a file and set `process.env` accordingly. Both of these forms are equivalent. 107 | 108 | ```js 109 | env(file: string) => EnvStream 110 | env({file: string}) => EnvStream 111 | ``` 112 | 113 | Set one or more hardcoded values in `process.env` directly. 114 | 115 | ```js 116 | env({vars: Object}) => EnvStream 117 | env.set(vars: Object) => EnvStream 118 | ``` 119 | 120 | Parse a file, overriding some of its variables. 121 | 122 | ```js 123 | env({ 124 | // file to read 125 | file: string, 126 | 127 | // overrides 128 | vars: Object, 129 | }) => EnvStream 130 | ``` 131 | 132 | Parse a file with a custom parser. 133 | 134 | ```js 135 | env({ 136 | // file to read 137 | file: string, 138 | 139 | // custom handling, `contents` is the file's contents 140 | handler: (contents: string) => Object, 141 | 142 | // optional overrides 143 | vars?: Object, 144 | }) => EnvStream 145 | ``` 146 | 147 | Parse a file as a different type. 148 | 149 | ```js 150 | env({ 151 | // file to read 152 | file: string, 153 | 154 | // Treat it like this type. See `options.type` for limitations. 155 | type: string, 156 | 157 | // overrides 158 | vars?: Object, 159 | }) => EnvStream 160 | ``` 161 | 162 | ### `file`, `options.file` 163 | 164 | The `file` option loads the file's contents automatically, calling `require` if it isn't a `.ini` file or if there is no `handler`. You can omit the extension as far as `require` allows if it's already registered, since this uses `require` under the hood as a fallback. 165 | 166 | ```js 167 | // .env.json 168 | { 169 | MONGO_URI: "mongodb://localhost:27017/testdb" 170 | } 171 | 172 | // .env.js 173 | module.exports = { 174 | MONGO_URI: "mongodb://localhost:27017/testdb", 175 | }; 176 | 177 | // gulpfile.js 178 | var env = require('gulp-env'); 179 | 180 | process.env.MONGO_URI === "mongodb://localhost:27017/testdb"; // maybe false 181 | 182 | // Any of these will work: 183 | env(".env"); // if the file can be found via `require` 184 | env(".env.json"); 185 | env({file: ".env"}); // if the file can be found via `require` 186 | env({file: ".env.json"}); 187 | 188 | process.env.MONGO_URI === "mongodb://localhost:27017/testdb"; // true 189 | ``` 190 | 191 | ### `options.vars` 192 | 193 | Properties on this object overwrite all existing external properties given by file loading, handlers, etc. All of these will also be added to `process.env`. 194 | 195 | ```js 196 | // gulpfile.js 197 | var env = require('gulp-env'); 198 | env({ 199 | file: 'env.ini', 200 | vars: { 201 | MONGO_URI: "mongodb://localhost:27017/testdb-for-british-eyes-only", 202 | PORT: 9001 203 | } 204 | }); 205 | ``` 206 | 207 | For the case of just setting environment variables programmatically, you can use `env.set`. 208 | 209 | ```js 210 | // These two are equivalent. They both can also be used in Gulp streams. 211 | env({vars: vars}); 212 | env.set(vars); 213 | ``` 214 | 215 | ### `options.handler` 216 | 217 | This customizes the parsing of the file. If this is given, the extension name is ignored, and the handler itself is directly called. This is very useful in cases where this module doesn't already support the format. Internally, the module uses this hook for its INI and JSON readers. 218 | 219 | The function, if given, is called with two arguments: 220 | 221 | - `contents` - the file's contents 222 | - `filename` - the file's name 223 | 224 | Notes: 225 | 226 | - You don't need this if the file type itself is already registered in `require.extensions`. 227 | - If the file doesn't exist, then `contents` is undefined. `filename` is still passed, though. 228 | - If the extension is omitted, then `filename` reflects that, i.e. the extension is omitted. 229 | 230 | ```coffee 231 | # CSON is frequently used in CoffeeScript projects. Why not use that? 232 | env = require 'gulp-env' 233 | CSON = require 'cson-safe' 234 | 235 | env 236 | file: '.env.cson' 237 | handler: (contents) -> CSON.parse contents 238 | ``` 239 | 240 | ```js 241 | // Or, why can't we use YAML? 242 | var env = require('gulp-env'); 243 | var jsyaml = require('js-yaml'); 244 | 245 | env({ 246 | file: '.env.yaml', 247 | handler: function(contents, filename) { 248 | return jsyaml.safeLoad(contents, {filename: filename}); 249 | }, 250 | }); 251 | ``` 252 | 253 | ### `options.type` 254 | 255 | Treats the file input as if its extension was `type`. It doesn't work for `require`d files, since Node.js doesn't have hooks to do that, but it currently works for `json` and `ini` types. Others may potentially be added over time. If you think another one should be added, please, by all means, submit a PR. 256 | 257 | ```js 258 | var env = require('gulp-env'); 259 | 260 | env({ 261 | file: '.env', 262 | type: 'ini', 263 | }); 264 | 265 | // You can also specify it as an extension, as opposed to a type. 266 | env({ 267 | file: '.env', 268 | type: '.ini', 269 | }); 270 | ``` 271 | 272 | ### EnvStream 273 | 274 | Instances of this interface are returned for `env()` and `env.set()`. These are standard through2 object streams with the following extra methods: 275 | 276 | - Reset the environment to its former state synchronously. This is designed to be most useful outside of gulpfiles. It returns a boolean, true if any properties were reset, false otherwise. Pass a truthy value as an argument to forcefully restore, i.e. ignore conflicts. 277 | 278 | ```js 279 | envs.restore(force?: boolean) => boolean 280 | ``` 281 | 282 | - Reset the environment to its former state. Similar to `.restore()`, but is called after the incoming stream is flushed, i.e. after all previous Gulp plugins have had their effect on the stream. This is otherwise a no-op through2 object stream. The second version is analogous to `envs.restore(true)` 283 | 284 | ```js 285 | envs.reset => stream.Readable, stream.Writable 286 | envs.reset.force => stream.Readable, stream.Writable 287 | ``` 288 | 289 | Note that such environments can be nested. For example, the following will work: 290 | 291 | ```js 292 | process.env.NODE_ENV // undefined 293 | var env1 = env.set({NODE_ENV: "whatever"}); 294 | process.env.NODE_ENV // "whatever" 295 | var env2 = env.set({NODE_ENV: "something else"}); 296 | process.env.NODE_ENV // "something else" 297 | env2.restore(); 298 | process.env.NODE_ENV // "whatever" 299 | env1.restore(); 300 | process.env.NODE_ENV // undefined 301 | ``` 302 | 303 | Now, if two settings are restored out of order, conflicting keys (where the currently set value is not the same as the originally set for that version) are simply left as-is. This is the same with externally changed environment variables. 304 | 305 | ```js 306 | // unbalanced modifications 307 | process.env.NODE_ENV // undefined 308 | var env1 = env.set({NODE_ENV: "whatever"}); 309 | process.env.NODE_ENV // "whatever" 310 | var env2 = env.set({NODE_ENV: "something else"}); 311 | process.env.NODE_ENV // "something else" 312 | env1.restore(); 313 | process.env.NODE_ENV // "something else" 314 | env2.restore(); 315 | process.env.NODE_ENV // "whatever" 316 | 317 | // external modifications 318 | process.env.NODE_ENV // undefined 319 | var env1 = env.set({NODE_ENV: "whatever"}); 320 | process.env.NODE_ENV // "whatever" 321 | process.env.NODE_ENV = "something else"; 322 | env1.restore(); 323 | process.env.NODE_ENV // "something else" 324 | ``` 325 | 326 | Issues 327 | ======= 328 | 329 | Submit a new issue here in the [issue tracker](https://github.com/moveline/gulp-env/issues/new) 330 | 331 | Contributing 332 | ============= 333 | 334 | This aims for full test coverage. If you see something missing, please, by all means, [send a PR](https://github.com/moveline/gulp-env/compare). 335 | 336 | To run the tests, run `npm test`. The tests and their dependencies are written in `test/**`. 337 | -------------------------------------------------------------------------------- /gulp-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | declare module "gulp-env" { 4 | interface EnvironmentMapping { 5 | [key: string]: any; 6 | } 7 | 8 | interface ForceableStream extends NodeJS.ReadWriteStream { 9 | force: boolean; 10 | } 11 | 12 | interface EnvStream extends NodeJS.ReadWriteStream { 13 | reset: ForceableStream; 14 | restore(force?: boolean): boolean; 15 | } 16 | 17 | interface Env { 18 | (file: string): EnvStream; 19 | 20 | (options: { 21 | vars: EnvironmentMapping, 22 | }): EnvStream; 23 | 24 | (options: { 25 | file: string, 26 | handler?: (contents: string) => EnvironmentMapping, 27 | vars?: EnvironmentMapping, 28 | }): EnvStream; 29 | 30 | (options: { 31 | file: string, 32 | type: string, 33 | vars?: EnvironmentMapping, 34 | }): EnvStream; 35 | 36 | set(vars: EnvironmentMapping): EnvStream; 37 | } 38 | 39 | export default Env; 40 | } 41 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var fs = require('fs'); 4 | var path = require('path'); 5 | var ini = require('ini'); 6 | var through2 = require('through2'); 7 | var hasOwn = Object.prototype.hasOwnProperty; 8 | var exts = require.extensions; 9 | 10 | function extend(dest, src) { 11 | for (var prop in src) { 12 | if (hasOwn.call(src, prop)) { 13 | dest[prop] = src[prop]; 14 | } 15 | } 16 | } 17 | 18 | // Custom types...it should be easy to 19 | var types = { 20 | '.ini': ini.parse, 21 | '.json': JSON.parse, 22 | }; 23 | 24 | // Copied from Node.js core. 25 | function stripBOM(content) { 26 | // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) 27 | // because the buffer-to-string conversion in `fs.readFileSync()` 28 | // translates it to FEFF, the UTF-16 BOM. 29 | if (content.charCodeAt(0) === 0xFEFF) { 30 | content = content.slice(1); 31 | } 32 | return content; 33 | } 34 | 35 | function bind(handler) { 36 | return function (file) { 37 | try { 38 | return handler(stripBOM(fs.readFileSync(file, 'utf8'))); 39 | } catch (e) { 40 | e.message = file + ': ' + e.message; 41 | throw e; 42 | } 43 | }; 44 | } 45 | 46 | module.exports = env; 47 | function env(options) { 48 | var vars = {}; 49 | var added = false; 50 | 51 | if (typeof options !== 'object') { 52 | options = {file: options + ''}; 53 | } 54 | 55 | if (options.file) { 56 | var file = path.resolve(options.file); 57 | var type = options.type || path.extname(file); 58 | 59 | if (type && type[0] !== '.') { 60 | type = '.' + type; 61 | } 62 | 63 | var handler = null; 64 | 65 | if (options.handler) { 66 | handler = bind(options.handler); 67 | } else if (!type) { 68 | handler = require; 69 | } else if (types[type]) { 70 | handler = bind(types[type]); 71 | } else if (exts[type]) { 72 | handler = require; 73 | } else { 74 | throw new TypeError('gulp-env: Unknown type: ' + type); 75 | } 76 | 77 | extend(vars, handler(file)); 78 | added = true; 79 | } 80 | 81 | if (options.vars) { 82 | if (vars == null) { 83 | extend(vars, options.vars); 84 | } else { 85 | extend(vars, options.vars); 86 | } 87 | added = true; 88 | } 89 | 90 | return set(added ? vars : null); 91 | }; 92 | 93 | function noopPipe(chunk, enc, cb) { 94 | cb(null, chunk); 95 | } 96 | 97 | function noopFlush(cb) { 98 | cb() 99 | } 100 | 101 | function defaultRestore() { 102 | return false; 103 | } 104 | 105 | function once(f) { 106 | var reference = function () { 107 | f(); 108 | reference = noopFlush; 109 | return reference.apply(this, arguments); 110 | }; 111 | return reference; 112 | } 113 | 114 | function makeOld(vars) { 115 | var old = {}; 116 | for (var i in vars) { 117 | if (hasOwn.call(vars, i) && hasOwn.call(process.env, i)) { 118 | old[i] = process.env[i]; 119 | } 120 | } 121 | return old; 122 | } 123 | 124 | function restoreOld(vars, old, force) { 125 | var res = false; 126 | for (var i in vars) { 127 | if (hasOwn.call(vars, i)) { 128 | if (force) { 129 | if (hasOwn.call(old, i)) { 130 | process.env[i] = old[i]; 131 | res = true; 132 | } else { 133 | delete process.env[i]; 134 | } 135 | } else if (process.env[i] === '' + vars[i]) { 136 | if (hasOwn.call(old, i)) { 137 | process.env[i] = old[i]; 138 | res = true; 139 | } else { 140 | delete process.env[i]; 141 | } 142 | } 143 | } 144 | } 145 | return res; 146 | } 147 | 148 | env.set = set; 149 | function set(vars) { 150 | var ret = through2.obj(); 151 | 152 | if (vars != null) { 153 | var old = makeOld(vars); 154 | extend(process.env, vars); 155 | var restore = ret.restore = restoreOld.bind(null, vars, old); 156 | 157 | ret.reset = through2.obj(noopPipe, once(restore)); 158 | ret.reset.force = through2.obj(noopPipe, once(restore.bind(null, true))); 159 | } 160 | 161 | return ret; 162 | } 163 | -------------------------------------------------------------------------------- /node.d.ts: -------------------------------------------------------------------------------- 1 | // Type definitions for Node.js v0.12.0 2 | // Project: http://nodejs.org/ 3 | // Definitions by: Microsoft TypeScript , DefinitelyTyped 4 | // Definitions: https://github.com/borisyankov/DefinitelyTyped 5 | 6 | /************************************************ 7 | * * 8 | * Node.js v0.12.0 API * 9 | * * 10 | ************************************************/ 11 | 12 | /************************************************ 13 | * * 14 | * GLOBAL * 15 | * * 16 | ************************************************/ 17 | declare var process: NodeJS.Process; 18 | declare var global: NodeJS.Global; 19 | 20 | declare var __filename: string; 21 | declare var __dirname: string; 22 | 23 | declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; 24 | declare function clearTimeout(timeoutId: NodeJS.Timer): void; 25 | declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; 26 | declare function clearInterval(intervalId: NodeJS.Timer): void; 27 | declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; 28 | declare function clearImmediate(immediateId: any): void; 29 | 30 | declare var require: { 31 | (id: string): any; 32 | resolve(id:string): string; 33 | cache: any; 34 | extensions: any; 35 | main: any; 36 | }; 37 | 38 | declare var module: { 39 | exports: any; 40 | require(id: string): any; 41 | id: string; 42 | filename: string; 43 | loaded: boolean; 44 | parent: any; 45 | children: any[]; 46 | }; 47 | 48 | // Same as module.exports 49 | declare var exports: any; 50 | declare var SlowBuffer: { 51 | new (str: string, encoding?: string): Buffer; 52 | new (size: number): Buffer; 53 | new (size: Uint8Array): Buffer; 54 | new (array: any[]): Buffer; 55 | prototype: Buffer; 56 | isBuffer(obj: any): boolean; 57 | byteLength(string: string, encoding?: string): number; 58 | concat(list: Buffer[], totalLength?: number): Buffer; 59 | }; 60 | 61 | 62 | // Buffer class 63 | interface Buffer extends NodeBuffer {} 64 | 65 | /** 66 | * Raw data is stored in instances of the Buffer class. 67 | * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. 68 | * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' 69 | */ 70 | declare var Buffer: { 71 | /** 72 | * Allocates a new buffer containing the given {str}. 73 | * 74 | * @param str String to store in buffer. 75 | * @param encoding encoding to use, optional. Default is 'utf8' 76 | */ 77 | new (str: string, encoding?: string): Buffer; 78 | /** 79 | * Allocates a new buffer of {size} octets. 80 | * 81 | * @param size count of octets to allocate. 82 | */ 83 | new (size: number): Buffer; 84 | /** 85 | * Allocates a new buffer containing the given {array} of octets. 86 | * 87 | * @param array The octets to store. 88 | */ 89 | new (array: Uint8Array): Buffer; 90 | /** 91 | * Allocates a new buffer containing the given {array} of octets. 92 | * 93 | * @param array The octets to store. 94 | */ 95 | new (array: any[]): Buffer; 96 | prototype: Buffer; 97 | /** 98 | * Returns true if {obj} is a Buffer 99 | * 100 | * @param obj object to test. 101 | */ 102 | isBuffer(obj: any): boolean; 103 | /** 104 | * Returns true if {encoding} is a valid encoding argument. 105 | * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' 106 | * 107 | * @param encoding string to test. 108 | */ 109 | isEncoding(encoding: string): boolean; 110 | /** 111 | * Gives the actual byte length of a string. encoding defaults to 'utf8'. 112 | * This is not the same as String.prototype.length since that returns the number of characters in a string. 113 | * 114 | * @param string string to test. 115 | * @param encoding encoding used to evaluate (defaults to 'utf8') 116 | */ 117 | byteLength(string: string, encoding?: string): number; 118 | /** 119 | * Returns a buffer which is the result of concatenating all the buffers in the list together. 120 | * 121 | * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. 122 | * If the list has exactly one item, then the first item of the list is returned. 123 | * If the list has more than one item, then a new Buffer is created. 124 | * 125 | * @param list An array of Buffer objects to concatenate 126 | * @param totalLength Total length of the buffers when concatenated. 127 | * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. 128 | */ 129 | concat(list: Buffer[], totalLength?: number): Buffer; 130 | }; 131 | 132 | /************************************************ 133 | * * 134 | * GLOBAL INTERFACES * 135 | * * 136 | ************************************************/ 137 | declare module NodeJS { 138 | export interface ErrnoException extends Error { 139 | errno?: number; 140 | code?: string; 141 | path?: string; 142 | syscall?: string; 143 | } 144 | 145 | export interface EventEmitter { 146 | addListener(event: string, listener: Function): EventEmitter; 147 | on(event: string, listener: Function): EventEmitter; 148 | once(event: string, listener: Function): EventEmitter; 149 | removeListener(event: string, listener: Function): EventEmitter; 150 | removeAllListeners(event?: string): EventEmitter; 151 | setMaxListeners(n: number): void; 152 | listeners(event: string): Function[]; 153 | emit(event: string, ...args: any[]): boolean; 154 | } 155 | 156 | export interface ReadableStream extends EventEmitter { 157 | readable: boolean; 158 | read(size?: number): string|Buffer; 159 | setEncoding(encoding: string): void; 160 | pause(): void; 161 | resume(): void; 162 | pipe(destination: T, options?: { end?: boolean; }): T; 163 | unpipe(destination?: T): void; 164 | unshift(chunk: string): void; 165 | unshift(chunk: Buffer): void; 166 | wrap(oldStream: ReadableStream): ReadableStream; 167 | } 168 | 169 | export interface WritableStream extends EventEmitter { 170 | writable: boolean; 171 | write(buffer: Buffer, cb?: Function): boolean; 172 | write(str: string, cb?: Function): boolean; 173 | write(str: string, encoding?: string, cb?: Function): boolean; 174 | end(): void; 175 | end(buffer: Buffer, cb?: Function): void; 176 | end(str: string, cb?: Function): void; 177 | end(str: string, encoding?: string, cb?: Function): void; 178 | } 179 | 180 | export interface ReadWriteStream extends ReadableStream, WritableStream {} 181 | 182 | export interface Process extends EventEmitter { 183 | stdout: WritableStream; 184 | stderr: WritableStream; 185 | stdin: ReadableStream; 186 | argv: string[]; 187 | execPath: string; 188 | abort(): void; 189 | chdir(directory: string): void; 190 | cwd(): string; 191 | env: any; 192 | exit(code?: number): void; 193 | getgid(): number; 194 | setgid(id: number): void; 195 | setgid(id: string): void; 196 | getuid(): number; 197 | setuid(id: number): void; 198 | setuid(id: string): void; 199 | version: string; 200 | versions: { 201 | http_parser: string; 202 | node: string; 203 | v8: string; 204 | ares: string; 205 | uv: string; 206 | zlib: string; 207 | openssl: string; 208 | }; 209 | config: { 210 | target_defaults: { 211 | cflags: any[]; 212 | default_configuration: string; 213 | defines: string[]; 214 | include_dirs: string[]; 215 | libraries: string[]; 216 | }; 217 | variables: { 218 | clang: number; 219 | host_arch: string; 220 | node_install_npm: boolean; 221 | node_install_waf: boolean; 222 | node_prefix: string; 223 | node_shared_openssl: boolean; 224 | node_shared_v8: boolean; 225 | node_shared_zlib: boolean; 226 | node_use_dtrace: boolean; 227 | node_use_etw: boolean; 228 | node_use_openssl: boolean; 229 | target_arch: string; 230 | v8_no_strict_aliasing: number; 231 | v8_use_snapshot: boolean; 232 | visibility: string; 233 | }; 234 | }; 235 | kill(pid: number, signal?: string): void; 236 | pid: number; 237 | title: string; 238 | arch: string; 239 | platform: string; 240 | memoryUsage(): { rss: number; heapTotal: number; heapUsed: number; }; 241 | nextTick(callback: Function): void; 242 | umask(mask?: number): number; 243 | uptime(): number; 244 | hrtime(time?:number[]): number[]; 245 | 246 | // Worker 247 | send?(message: any, sendHandle?: any): void; 248 | } 249 | 250 | export interface Global { 251 | Array: typeof Array; 252 | ArrayBuffer: typeof ArrayBuffer; 253 | Boolean: typeof Boolean; 254 | Buffer: typeof Buffer; 255 | DataView: typeof DataView; 256 | Date: typeof Date; 257 | Error: typeof Error; 258 | EvalError: typeof EvalError; 259 | Float32Array: typeof Float32Array; 260 | Float64Array: typeof Float64Array; 261 | Function: typeof Function; 262 | GLOBAL: Global; 263 | Infinity: typeof Infinity; 264 | Int16Array: typeof Int16Array; 265 | Int32Array: typeof Int32Array; 266 | Int8Array: typeof Int8Array; 267 | Intl: typeof Intl; 268 | JSON: typeof JSON; 269 | Map: typeof Map; 270 | Math: typeof Math; 271 | NaN: typeof NaN; 272 | Number: typeof Number; 273 | Object: typeof Object; 274 | Promise: Function; 275 | RangeError: typeof RangeError; 276 | ReferenceError: typeof ReferenceError; 277 | RegExp: typeof RegExp; 278 | Set: typeof Set; 279 | String: typeof String; 280 | Symbol: Function; 281 | SyntaxError: typeof SyntaxError; 282 | TypeError: typeof TypeError; 283 | URIError: typeof URIError; 284 | Uint16Array: typeof Uint16Array; 285 | Uint32Array: typeof Uint32Array; 286 | Uint8Array: typeof Uint8Array; 287 | Uint8ClampedArray: Function; 288 | WeakMap: typeof WeakMap; 289 | WeakSet: Function; 290 | clearImmediate: (immediateId: any) => void; 291 | clearInterval: (intervalId: NodeJS.Timer) => void; 292 | clearTimeout: (timeoutId: NodeJS.Timer) => void; 293 | console: typeof console; 294 | decodeURI: typeof decodeURI; 295 | decodeURIComponent: typeof decodeURIComponent; 296 | encodeURI: typeof encodeURI; 297 | encodeURIComponent: typeof encodeURIComponent; 298 | escape: (str: string) => string; 299 | eval: typeof eval; 300 | global: Global; 301 | isFinite: typeof isFinite; 302 | isNaN: typeof isNaN; 303 | parseFloat: typeof parseFloat; 304 | parseInt: typeof parseInt; 305 | process: Process; 306 | root: Global; 307 | setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any; 308 | setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; 309 | setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; 310 | undefined: typeof undefined; 311 | unescape: (str: string) => string; 312 | gc: () => void; 313 | } 314 | 315 | export interface Timer { 316 | ref() : void; 317 | unref() : void; 318 | } 319 | } 320 | 321 | /** 322 | * @deprecated 323 | */ 324 | interface NodeBuffer { 325 | [index: number]: number; 326 | write(string: string, offset?: number, length?: number, encoding?: string): number; 327 | toString(encoding?: string, start?: number, end?: number): string; 328 | toJSON(): any; 329 | length: number; 330 | copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; 331 | slice(start?: number, end?: number): Buffer; 332 | readUInt8(offset: number, noAsset?: boolean): number; 333 | readUInt16LE(offset: number, noAssert?: boolean): number; 334 | readUInt16BE(offset: number, noAssert?: boolean): number; 335 | readUInt32LE(offset: number, noAssert?: boolean): number; 336 | readUInt32BE(offset: number, noAssert?: boolean): number; 337 | readInt8(offset: number, noAssert?: boolean): number; 338 | readInt16LE(offset: number, noAssert?: boolean): number; 339 | readInt16BE(offset: number, noAssert?: boolean): number; 340 | readInt32LE(offset: number, noAssert?: boolean): number; 341 | readInt32BE(offset: number, noAssert?: boolean): number; 342 | readFloatLE(offset: number, noAssert?: boolean): number; 343 | readFloatBE(offset: number, noAssert?: boolean): number; 344 | readDoubleLE(offset: number, noAssert?: boolean): number; 345 | readDoubleBE(offset: number, noAssert?: boolean): number; 346 | writeUInt8(value: number, offset: number, noAssert?: boolean): void; 347 | writeUInt16LE(value: number, offset: number, noAssert?: boolean): void; 348 | writeUInt16BE(value: number, offset: number, noAssert?: boolean): void; 349 | writeUInt32LE(value: number, offset: number, noAssert?: boolean): void; 350 | writeUInt32BE(value: number, offset: number, noAssert?: boolean): void; 351 | writeInt8(value: number, offset: number, noAssert?: boolean): void; 352 | writeInt16LE(value: number, offset: number, noAssert?: boolean): void; 353 | writeInt16BE(value: number, offset: number, noAssert?: boolean): void; 354 | writeInt32LE(value: number, offset: number, noAssert?: boolean): void; 355 | writeInt32BE(value: number, offset: number, noAssert?: boolean): void; 356 | writeFloatLE(value: number, offset: number, noAssert?: boolean): void; 357 | writeFloatBE(value: number, offset: number, noAssert?: boolean): void; 358 | writeDoubleLE(value: number, offset: number, noAssert?: boolean): void; 359 | writeDoubleBE(value: number, offset: number, noAssert?: boolean): void; 360 | fill(value: any, offset?: number, end?: number): void; 361 | } 362 | 363 | /************************************************ 364 | * * 365 | * MODULES * 366 | * * 367 | ************************************************/ 368 | declare module "buffer" { 369 | export var INSPECT_MAX_BYTES: number; 370 | } 371 | 372 | declare module "querystring" { 373 | export function stringify(obj: any, sep?: string, eq?: string): string; 374 | export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; 375 | export function escape(str: string): string; 376 | export function unescape(str: string): string; 377 | } 378 | 379 | declare module "events" { 380 | export class EventEmitter implements NodeJS.EventEmitter { 381 | static listenerCount(emitter: EventEmitter, event: string): number; 382 | 383 | addListener(event: string, listener: Function): EventEmitter; 384 | on(event: string, listener: Function): EventEmitter; 385 | once(event: string, listener: Function): EventEmitter; 386 | removeListener(event: string, listener: Function): EventEmitter; 387 | removeAllListeners(event?: string): EventEmitter; 388 | setMaxListeners(n: number): void; 389 | listeners(event: string): Function[]; 390 | emit(event: string, ...args: any[]): boolean; 391 | } 392 | } 393 | 394 | declare module "http" { 395 | import events = require("events"); 396 | import net = require("net"); 397 | import stream = require("stream"); 398 | 399 | export interface Server extends events.EventEmitter { 400 | listen(port: number, hostname?: string, backlog?: number, callback?: Function): Server; 401 | listen(port: number, hostname?: string, callback?: Function): Server; 402 | listen(path: string, callback?: Function): Server; 403 | listen(handle: any, listeningListener?: Function): Server; 404 | close(cb?: any): Server; 405 | address(): { port: number; family: string; address: string; }; 406 | maxHeadersCount: number; 407 | } 408 | /** 409 | * @deprecated Use IncomingMessage 410 | */ 411 | export interface ServerRequest extends IncomingMessage { 412 | connection: net.Socket; 413 | } 414 | export interface ServerResponse extends events.EventEmitter, stream.Writable { 415 | // Extended base methods 416 | write(buffer: Buffer): boolean; 417 | write(buffer: Buffer, cb?: Function): boolean; 418 | write(str: string, cb?: Function): boolean; 419 | write(str: string, encoding?: string, cb?: Function): boolean; 420 | write(str: string, encoding?: string, fd?: string): boolean; 421 | 422 | writeContinue(): void; 423 | writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; 424 | writeHead(statusCode: number, headers?: any): void; 425 | statusCode: number; 426 | setHeader(name: string, value: string): void; 427 | sendDate: boolean; 428 | getHeader(name: string): string; 429 | removeHeader(name: string): void; 430 | write(chunk: any, encoding?: string): any; 431 | addTrailers(headers: any): void; 432 | 433 | // Extended base methods 434 | end(): void; 435 | end(buffer: Buffer, cb?: Function): void; 436 | end(str: string, cb?: Function): void; 437 | end(str: string, encoding?: string, cb?: Function): void; 438 | end(data?: any, encoding?: string): void; 439 | } 440 | export interface ClientRequest extends events.EventEmitter, stream.Writable { 441 | // Extended base methods 442 | write(buffer: Buffer): boolean; 443 | write(buffer: Buffer, cb?: Function): boolean; 444 | write(str: string, cb?: Function): boolean; 445 | write(str: string, encoding?: string, cb?: Function): boolean; 446 | write(str: string, encoding?: string, fd?: string): boolean; 447 | 448 | write(chunk: any, encoding?: string): void; 449 | abort(): void; 450 | setTimeout(timeout: number, callback?: Function): void; 451 | setNoDelay(noDelay?: boolean): void; 452 | setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; 453 | 454 | // Extended base methods 455 | end(): void; 456 | end(buffer: Buffer, cb?: Function): void; 457 | end(str: string, cb?: Function): void; 458 | end(str: string, encoding?: string, cb?: Function): void; 459 | end(data?: any, encoding?: string): void; 460 | } 461 | export interface IncomingMessage extends events.EventEmitter, stream.Readable { 462 | httpVersion: string; 463 | headers: any; 464 | rawHeaders: string[]; 465 | trailers: any; 466 | rawTrailers: any; 467 | setTimeout(msecs: number, callback: Function): NodeJS.Timer; 468 | /** 469 | * Only valid for request obtained from http.Server. 470 | */ 471 | method?: string; 472 | /** 473 | * Only valid for request obtained from http.Server. 474 | */ 475 | url?: string; 476 | /** 477 | * Only valid for response obtained from http.ClientRequest. 478 | */ 479 | statusCode?: number; 480 | /** 481 | * Only valid for response obtained from http.ClientRequest. 482 | */ 483 | statusMessage?: string; 484 | socket: net.Socket; 485 | } 486 | /** 487 | * @deprecated Use IncomingMessage 488 | */ 489 | export interface ClientResponse extends IncomingMessage { } 490 | 491 | export interface AgentOptions { 492 | /** 493 | * Keep sockets around in a pool to be used by other requests in the future. Default = false 494 | */ 495 | keepAlive?: boolean; 496 | /** 497 | * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. 498 | * Only relevant if keepAlive is set to true. 499 | */ 500 | keepAliveMsecs?: number; 501 | /** 502 | * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity 503 | */ 504 | maxSockets?: number; 505 | /** 506 | * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. 507 | */ 508 | maxFreeSockets?: number; 509 | } 510 | 511 | export class Agent { 512 | maxSockets: number; 513 | sockets: any; 514 | requests: any; 515 | 516 | constructor(opts?: AgentOptions); 517 | 518 | /** 519 | * Destroy any sockets that are currently in use by the agent. 520 | * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, 521 | * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, 522 | * sockets may hang open for quite a long time before the server terminates them. 523 | */ 524 | destroy(): void; 525 | } 526 | 527 | export var STATUS_CODES: { 528 | [errorCode: number]: string; 529 | [errorCode: string]: string; 530 | }; 531 | export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) =>void ): Server; 532 | export function createClient(port?: number, host?: string): any; 533 | export function request(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; 534 | export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; 535 | export var globalAgent: Agent; 536 | } 537 | 538 | declare module "cluster" { 539 | import child = require("child_process"); 540 | import events = require("events"); 541 | 542 | export interface ClusterSettings { 543 | exec?: string; 544 | args?: string[]; 545 | silent?: boolean; 546 | } 547 | 548 | export class Worker extends events.EventEmitter { 549 | id: string; 550 | process: child.ChildProcess; 551 | suicide: boolean; 552 | send(message: any, sendHandle?: any): void; 553 | kill(signal?: string): void; 554 | destroy(signal?: string): void; 555 | disconnect(): void; 556 | } 557 | 558 | export var settings: ClusterSettings; 559 | export var isMaster: boolean; 560 | export var isWorker: boolean; 561 | export function setupMaster(settings?: ClusterSettings): void; 562 | export function fork(env?: any): Worker; 563 | export function disconnect(callback?: Function): void; 564 | export var worker: Worker; 565 | export var workers: Worker[]; 566 | 567 | // Event emitter 568 | export function addListener(event: string, listener: Function): void; 569 | export function on(event: string, listener: Function): any; 570 | export function once(event: string, listener: Function): void; 571 | export function removeListener(event: string, listener: Function): void; 572 | export function removeAllListeners(event?: string): void; 573 | export function setMaxListeners(n: number): void; 574 | export function listeners(event: string): Function[]; 575 | export function emit(event: string, ...args: any[]): boolean; 576 | } 577 | 578 | declare module "zlib" { 579 | import stream = require("stream"); 580 | export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } 581 | 582 | export interface Gzip extends stream.Transform { } 583 | export interface Gunzip extends stream.Transform { } 584 | export interface Deflate extends stream.Transform { } 585 | export interface Inflate extends stream.Transform { } 586 | export interface DeflateRaw extends stream.Transform { } 587 | export interface InflateRaw extends stream.Transform { } 588 | export interface Unzip extends stream.Transform { } 589 | 590 | export function createGzip(options?: ZlibOptions): Gzip; 591 | export function createGunzip(options?: ZlibOptions): Gunzip; 592 | export function createDeflate(options?: ZlibOptions): Deflate; 593 | export function createInflate(options?: ZlibOptions): Inflate; 594 | export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; 595 | export function createInflateRaw(options?: ZlibOptions): InflateRaw; 596 | export function createUnzip(options?: ZlibOptions): Unzip; 597 | 598 | export function deflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; 599 | export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; 600 | export function gzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; 601 | export function gunzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; 602 | export function inflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; 603 | export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; 604 | export function unzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; 605 | 606 | // Constants 607 | export var Z_NO_FLUSH: number; 608 | export var Z_PARTIAL_FLUSH: number; 609 | export var Z_SYNC_FLUSH: number; 610 | export var Z_FULL_FLUSH: number; 611 | export var Z_FINISH: number; 612 | export var Z_BLOCK: number; 613 | export var Z_TREES: number; 614 | export var Z_OK: number; 615 | export var Z_STREAM_END: number; 616 | export var Z_NEED_DICT: number; 617 | export var Z_ERRNO: number; 618 | export var Z_STREAM_ERROR: number; 619 | export var Z_DATA_ERROR: number; 620 | export var Z_MEM_ERROR: number; 621 | export var Z_BUF_ERROR: number; 622 | export var Z_VERSION_ERROR: number; 623 | export var Z_NO_COMPRESSION: number; 624 | export var Z_BEST_SPEED: number; 625 | export var Z_BEST_COMPRESSION: number; 626 | export var Z_DEFAULT_COMPRESSION: number; 627 | export var Z_FILTERED: number; 628 | export var Z_HUFFMAN_ONLY: number; 629 | export var Z_RLE: number; 630 | export var Z_FIXED: number; 631 | export var Z_DEFAULT_STRATEGY: number; 632 | export var Z_BINARY: number; 633 | export var Z_TEXT: number; 634 | export var Z_ASCII: number; 635 | export var Z_UNKNOWN: number; 636 | export var Z_DEFLATED: number; 637 | export var Z_NULL: number; 638 | } 639 | 640 | declare module "os" { 641 | export function tmpdir(): string; 642 | export function hostname(): string; 643 | export function type(): string; 644 | export function platform(): string; 645 | export function arch(): string; 646 | export function release(): string; 647 | export function uptime(): number; 648 | export function loadavg(): number[]; 649 | export function totalmem(): number; 650 | export function freemem(): number; 651 | export function cpus(): { model: string; speed: number; times: { user: number; nice: number; sys: number; idle: number; irq: number; }; }[]; 652 | export function networkInterfaces(): any; 653 | export var EOL: string; 654 | } 655 | 656 | declare module "https" { 657 | import tls = require("tls"); 658 | import events = require("events"); 659 | import http = require("http"); 660 | 661 | export interface ServerOptions { 662 | pfx?: any; 663 | key?: any; 664 | passphrase?: string; 665 | cert?: any; 666 | ca?: any; 667 | crl?: any; 668 | ciphers?: string; 669 | honorCipherOrder?: boolean; 670 | requestCert?: boolean; 671 | rejectUnauthorized?: boolean; 672 | NPNProtocols?: any; 673 | SNICallback?: (servername: string) => any; 674 | } 675 | 676 | export interface RequestOptions { 677 | host?: string; 678 | hostname?: string; 679 | port?: number; 680 | path?: string; 681 | method?: string; 682 | headers?: any; 683 | auth?: string; 684 | agent?: any; 685 | pfx?: any; 686 | key?: any; 687 | passphrase?: string; 688 | cert?: any; 689 | ca?: any; 690 | ciphers?: string; 691 | rejectUnauthorized?: boolean; 692 | } 693 | 694 | export interface Agent { 695 | maxSockets: number; 696 | sockets: any; 697 | requests: any; 698 | } 699 | export var Agent: { 700 | new (options?: RequestOptions): Agent; 701 | }; 702 | export interface Server extends tls.Server { } 703 | export function createServer(options: ServerOptions, requestListener?: Function): Server; 704 | export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest; 705 | export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest; 706 | export var globalAgent: Agent; 707 | } 708 | 709 | declare module "punycode" { 710 | export function decode(string: string): string; 711 | export function encode(string: string): string; 712 | export function toUnicode(domain: string): string; 713 | export function toASCII(domain: string): string; 714 | export var ucs2: ucs2; 715 | interface ucs2 { 716 | decode(string: string): string; 717 | encode(codePoints: number[]): string; 718 | } 719 | export var version: any; 720 | } 721 | 722 | declare module "repl" { 723 | import stream = require("stream"); 724 | import events = require("events"); 725 | 726 | export interface ReplOptions { 727 | prompt?: string; 728 | input?: NodeJS.ReadableStream; 729 | output?: NodeJS.WritableStream; 730 | terminal?: boolean; 731 | eval?: Function; 732 | useColors?: boolean; 733 | useGlobal?: boolean; 734 | ignoreUndefined?: boolean; 735 | writer?: Function; 736 | } 737 | export function start(options: ReplOptions): events.EventEmitter; 738 | } 739 | 740 | declare module "readline" { 741 | import events = require("events"); 742 | import stream = require("stream"); 743 | 744 | export interface ReadLine extends events.EventEmitter { 745 | setPrompt(prompt: string, length: number): void; 746 | prompt(preserveCursor?: boolean): void; 747 | question(query: string, callback: Function): void; 748 | pause(): void; 749 | resume(): void; 750 | close(): void; 751 | write(data: any, key?: any): void; 752 | } 753 | export interface ReadLineOptions { 754 | input: NodeJS.ReadableStream; 755 | output: NodeJS.WritableStream; 756 | completer?: Function; 757 | terminal?: boolean; 758 | } 759 | export function createInterface(options: ReadLineOptions): ReadLine; 760 | } 761 | 762 | declare module "vm" { 763 | export interface Context { } 764 | export interface Script { 765 | runInThisContext(): void; 766 | runInNewContext(sandbox?: Context): void; 767 | } 768 | export function runInThisContext(code: string, filename?: string): void; 769 | export function runInNewContext(code: string, sandbox?: Context, filename?: string): void; 770 | export function runInContext(code: string, context: Context, filename?: string): void; 771 | export function createContext(initSandbox?: Context): Context; 772 | export function createScript(code: string, filename?: string): Script; 773 | } 774 | 775 | declare module "child_process" { 776 | import events = require("events"); 777 | import stream = require("stream"); 778 | 779 | export interface ChildProcess extends events.EventEmitter { 780 | stdin: stream.Writable; 781 | stdout: stream.Readable; 782 | stderr: stream.Readable; 783 | pid: number; 784 | kill(signal?: string): void; 785 | send(message: any, sendHandle?: any): void; 786 | disconnect(): void; 787 | } 788 | 789 | export function spawn(command: string, args?: string[], options?: { 790 | cwd?: string; 791 | stdio?: any; 792 | custom?: any; 793 | env?: any; 794 | detached?: boolean; 795 | }): ChildProcess; 796 | export function exec(command: string, options: { 797 | cwd?: string; 798 | stdio?: any; 799 | customFds?: any; 800 | env?: any; 801 | encoding?: string; 802 | timeout?: number; 803 | maxBuffer?: number; 804 | killSignal?: string; 805 | }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; 806 | export function exec(command: string, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; 807 | export function execFile(file: string, 808 | callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; 809 | export function execFile(file: string, args?: string[], 810 | callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; 811 | export function execFile(file: string, args?: string[], options?: { 812 | cwd?: string; 813 | stdio?: any; 814 | customFds?: any; 815 | env?: any; 816 | encoding?: string; 817 | timeout?: number; 818 | maxBuffer?: string; 819 | killSignal?: string; 820 | }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; 821 | export function fork(modulePath: string, args?: string[], options?: { 822 | cwd?: string; 823 | env?: any; 824 | encoding?: string; 825 | }): ChildProcess; 826 | export function execSync(command: string, options?: { 827 | cwd?: string; 828 | input?: string|Buffer; 829 | stdio?: any; 830 | env?: any; 831 | uid?: number; 832 | gid?: number; 833 | timeout?: number; 834 | maxBuffer?: number; 835 | killSignal?: string; 836 | encoding?: string; 837 | }): ChildProcess; 838 | export function execFileSync(command: string, args?: string[], options?: { 839 | cwd?: string; 840 | input?: string|Buffer; 841 | stdio?: any; 842 | env?: any; 843 | uid?: number; 844 | gid?: number; 845 | timeout?: number; 846 | maxBuffer?: number; 847 | killSignal?: string; 848 | encoding?: string; 849 | }): ChildProcess; 850 | } 851 | 852 | declare module "url" { 853 | export interface Url { 854 | href: string; 855 | protocol: string; 856 | auth: string; 857 | hostname: string; 858 | port: string; 859 | host: string; 860 | pathname: string; 861 | search: string; 862 | query: any; // string | Object 863 | slashes: boolean; 864 | hash?: string; 865 | path?: string; 866 | } 867 | 868 | export interface UrlOptions { 869 | protocol?: string; 870 | auth?: string; 871 | hostname?: string; 872 | port?: string; 873 | host?: string; 874 | pathname?: string; 875 | search?: string; 876 | query?: any; 877 | hash?: string; 878 | path?: string; 879 | } 880 | 881 | export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url; 882 | export function format(url: UrlOptions): string; 883 | export function resolve(from: string, to: string): string; 884 | } 885 | 886 | declare module "dns" { 887 | export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string; 888 | export function lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string; 889 | export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[]; 890 | export function resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; 891 | export function resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; 892 | export function resolve6(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; 893 | export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; 894 | export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; 895 | export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; 896 | export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; 897 | export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; 898 | export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; 899 | } 900 | 901 | declare module "net" { 902 | import stream = require("stream"); 903 | 904 | export interface Socket extends stream.Duplex { 905 | // Extended base methods 906 | write(buffer: Buffer): boolean; 907 | write(buffer: Buffer, cb?: Function): boolean; 908 | write(str: string, cb?: Function): boolean; 909 | write(str: string, encoding?: string, cb?: Function): boolean; 910 | write(str: string, encoding?: string, fd?: string): boolean; 911 | 912 | connect(port: number, host?: string, connectionListener?: Function): void; 913 | connect(path: string, connectionListener?: Function): void; 914 | bufferSize: number; 915 | setEncoding(encoding?: string): void; 916 | write(data: any, encoding?: string, callback?: Function): void; 917 | destroy(): void; 918 | pause(): void; 919 | resume(): void; 920 | setTimeout(timeout: number, callback?: Function): void; 921 | setNoDelay(noDelay?: boolean): void; 922 | setKeepAlive(enable?: boolean, initialDelay?: number): void; 923 | address(): { port: number; family: string; address: string; }; 924 | unref(): void; 925 | ref(): void; 926 | 927 | remoteAddress: string; 928 | remoteFamily: string; 929 | remotePort: number; 930 | localAddress: string; 931 | localPort: number; 932 | bytesRead: number; 933 | bytesWritten: number; 934 | 935 | // Extended base methods 936 | end(): void; 937 | end(buffer: Buffer, cb?: Function): void; 938 | end(str: string, cb?: Function): void; 939 | end(str: string, encoding?: string, cb?: Function): void; 940 | end(data?: any, encoding?: string): void; 941 | } 942 | 943 | export var Socket: { 944 | new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; 945 | }; 946 | 947 | export interface Server extends Socket { 948 | listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server; 949 | listen(path: string, listeningListener?: Function): Server; 950 | listen(handle: any, listeningListener?: Function): Server; 951 | close(callback?: Function): Server; 952 | address(): { port: number; family: string; address: string; }; 953 | maxConnections: number; 954 | connections: number; 955 | } 956 | export function createServer(connectionListener?: (socket: Socket) =>void ): Server; 957 | export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) =>void ): Server; 958 | export function connect(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; 959 | export function connect(port: number, host?: string, connectionListener?: Function): Socket; 960 | export function connect(path: string, connectionListener?: Function): Socket; 961 | export function createConnection(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; 962 | export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; 963 | export function createConnection(path: string, connectionListener?: Function): Socket; 964 | export function isIP(input: string): number; 965 | export function isIPv4(input: string): boolean; 966 | export function isIPv6(input: string): boolean; 967 | } 968 | 969 | declare module "dgram" { 970 | import events = require("events"); 971 | 972 | interface RemoteInfo { 973 | address: string; 974 | port: number; 975 | size: number; 976 | } 977 | 978 | interface AddressInfo { 979 | address: string; 980 | family: string; 981 | port: number; 982 | } 983 | 984 | export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; 985 | 986 | interface Socket extends events.EventEmitter { 987 | send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; 988 | bind(port: number, address?: string, callback?: () => void): void; 989 | close(): void; 990 | address(): AddressInfo; 991 | setBroadcast(flag: boolean): void; 992 | setMulticastTTL(ttl: number): void; 993 | setMulticastLoopback(flag: boolean): void; 994 | addMembership(multicastAddress: string, multicastInterface?: string): void; 995 | dropMembership(multicastAddress: string, multicastInterface?: string): void; 996 | } 997 | } 998 | 999 | declare module "fs" { 1000 | import stream = require("stream"); 1001 | import events = require("events"); 1002 | 1003 | interface Stats { 1004 | isFile(): boolean; 1005 | isDirectory(): boolean; 1006 | isBlockDevice(): boolean; 1007 | isCharacterDevice(): boolean; 1008 | isSymbolicLink(): boolean; 1009 | isFIFO(): boolean; 1010 | isSocket(): boolean; 1011 | dev: number; 1012 | ino: number; 1013 | mode: number; 1014 | nlink: number; 1015 | uid: number; 1016 | gid: number; 1017 | rdev: number; 1018 | size: number; 1019 | blksize: number; 1020 | blocks: number; 1021 | atime: Date; 1022 | mtime: Date; 1023 | ctime: Date; 1024 | } 1025 | 1026 | interface FSWatcher extends events.EventEmitter { 1027 | close(): void; 1028 | } 1029 | 1030 | export interface ReadStream extends stream.Readable { 1031 | close(): void; 1032 | } 1033 | export interface WriteStream extends stream.Writable { 1034 | close(): void; 1035 | } 1036 | 1037 | /** 1038 | * Asynchronous rename. 1039 | * @param oldPath 1040 | * @param newPath 1041 | * @param callback No arguments other than a possible exception are given to the completion callback. 1042 | */ 1043 | export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; 1044 | /** 1045 | * Synchronous rename 1046 | * @param oldPath 1047 | * @param newPath 1048 | */ 1049 | export function renameSync(oldPath: string, newPath: string): void; 1050 | export function truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; 1051 | export function truncate(path: string, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 1052 | export function truncateSync(path: string, len?: number): void; 1053 | export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 1054 | export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 1055 | export function ftruncateSync(fd: number, len?: number): void; 1056 | export function chown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 1057 | export function chownSync(path: string, uid: number, gid: number): void; 1058 | export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 1059 | export function fchownSync(fd: number, uid: number, gid: number): void; 1060 | export function lchown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 1061 | export function lchownSync(path: string, uid: number, gid: number): void; 1062 | export function chmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 1063 | export function chmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; 1064 | export function chmodSync(path: string, mode: number): void; 1065 | export function chmodSync(path: string, mode: string): void; 1066 | export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 1067 | export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; 1068 | export function fchmodSync(fd: number, mode: number): void; 1069 | export function fchmodSync(fd: number, mode: string): void; 1070 | export function lchmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 1071 | export function lchmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; 1072 | export function lchmodSync(path: string, mode: number): void; 1073 | export function lchmodSync(path: string, mode: string): void; 1074 | export function stat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; 1075 | export function lstat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; 1076 | export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; 1077 | export function statSync(path: string): Stats; 1078 | export function lstatSync(path: string): Stats; 1079 | export function fstatSync(fd: number): Stats; 1080 | export function link(srcpath: string, dstpath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; 1081 | export function linkSync(srcpath: string, dstpath: string): void; 1082 | export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; 1083 | export function symlinkSync(srcpath: string, dstpath: string, type?: string): void; 1084 | export function readlink(path: string, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; 1085 | export function readlinkSync(path: string): string; 1086 | export function realpath(path: string, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; 1087 | export function realpath(path: string, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) =>any): void; 1088 | export function realpathSync(path: string, cache?: { [path: string]: string }): string; 1089 | /* 1090 | * Asynchronous unlink - deletes the file specified in {path} 1091 | * 1092 | * @param path 1093 | * @param callback No arguments other than a possible exception are given to the completion callback. 1094 | */ 1095 | export function unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; 1096 | /* 1097 | * Synchronous unlink - deletes the file specified in {path} 1098 | * 1099 | * @param path 1100 | */ 1101 | export function unlinkSync(path: string): void; 1102 | /* 1103 | * Asynchronous rmdir - removes the directory specified in {path} 1104 | * 1105 | * @param path 1106 | * @param callback No arguments other than a possible exception are given to the completion callback. 1107 | */ 1108 | export function rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; 1109 | /* 1110 | * Synchronous rmdir - removes the directory specified in {path} 1111 | * 1112 | * @param path 1113 | */ 1114 | export function rmdirSync(path: string): void; 1115 | /* 1116 | * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. 1117 | * 1118 | * @param path 1119 | * @param callback No arguments other than a possible exception are given to the completion callback. 1120 | */ 1121 | export function mkdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; 1122 | /* 1123 | * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. 1124 | * 1125 | * @param path 1126 | * @param mode 1127 | * @param callback No arguments other than a possible exception are given to the completion callback. 1128 | */ 1129 | export function mkdir(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 1130 | /* 1131 | * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. 1132 | * 1133 | * @param path 1134 | * @param mode 1135 | * @param callback No arguments other than a possible exception are given to the completion callback. 1136 | */ 1137 | export function mkdir(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; 1138 | /* 1139 | * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. 1140 | * 1141 | * @param path 1142 | * @param mode 1143 | * @param callback No arguments other than a possible exception are given to the completion callback. 1144 | */ 1145 | export function mkdirSync(path: string, mode?: number): void; 1146 | /* 1147 | * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. 1148 | * 1149 | * @param path 1150 | * @param mode 1151 | * @param callback No arguments other than a possible exception are given to the completion callback. 1152 | */ 1153 | export function mkdirSync(path: string, mode?: string): void; 1154 | export function readdir(path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; 1155 | export function readdirSync(path: string): string[]; 1156 | export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 1157 | export function closeSync(fd: number): void; 1158 | export function open(path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; 1159 | export function open(path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; 1160 | export function open(path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; 1161 | export function openSync(path: string, flags: string, mode?: number): number; 1162 | export function openSync(path: string, flags: string, mode?: string): number; 1163 | export function utimes(path: string, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 1164 | export function utimes(path: string, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; 1165 | export function utimesSync(path: string, atime: number, mtime: number): void; 1166 | export function utimesSync(path: string, atime: Date, mtime: Date): void; 1167 | export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 1168 | export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; 1169 | export function futimesSync(fd: number, atime: number, mtime: number): void; 1170 | export function futimesSync(fd: number, atime: Date, mtime: Date): void; 1171 | export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 1172 | export function fsyncSync(fd: number): void; 1173 | export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; 1174 | export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; 1175 | export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; 1176 | export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; 1177 | /* 1178 | * Asynchronous readFile - Asynchronously reads the entire contents of a file. 1179 | * 1180 | * @param fileName 1181 | * @param encoding 1182 | * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. 1183 | */ 1184 | export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; 1185 | /* 1186 | * Asynchronous readFile - Asynchronously reads the entire contents of a file. 1187 | * 1188 | * @param fileName 1189 | * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. 1190 | * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. 1191 | */ 1192 | export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void; 1193 | /* 1194 | * Asynchronous readFile - Asynchronously reads the entire contents of a file. 1195 | * 1196 | * @param fileName 1197 | * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. 1198 | * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. 1199 | */ 1200 | export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; 1201 | /* 1202 | * Asynchronous readFile - Asynchronously reads the entire contents of a file. 1203 | * 1204 | * @param fileName 1205 | * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. 1206 | */ 1207 | export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; 1208 | /* 1209 | * Synchronous readFile - Synchronously reads the entire contents of a file. 1210 | * 1211 | * @param fileName 1212 | * @param encoding 1213 | */ 1214 | export function readFileSync(filename: string, encoding: string): string; 1215 | /* 1216 | * Synchronous readFile - Synchronously reads the entire contents of a file. 1217 | * 1218 | * @param fileName 1219 | * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. 1220 | */ 1221 | export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; 1222 | /* 1223 | * Synchronous readFile - Synchronously reads the entire contents of a file. 1224 | * 1225 | * @param fileName 1226 | * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. 1227 | */ 1228 | export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; 1229 | export function writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; 1230 | export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; 1231 | export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; 1232 | export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; 1233 | export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; 1234 | export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; 1235 | export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; 1236 | export function appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; 1237 | export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; 1238 | export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; 1239 | export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void; 1240 | export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; 1241 | export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; 1242 | export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; 1243 | export function watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; 1244 | export function exists(path: string, callback?: (exists: boolean) => void): void; 1245 | export function existsSync(path: string): boolean; 1246 | export function createReadStream(path: string, options?: { 1247 | flags?: string; 1248 | encoding?: string; 1249 | fd?: string; 1250 | mode?: number; 1251 | bufferSize?: number; 1252 | }): ReadStream; 1253 | export function createReadStream(path: string, options?: { 1254 | flags?: string; 1255 | encoding?: string; 1256 | fd?: string; 1257 | mode?: string; 1258 | bufferSize?: number; 1259 | }): ReadStream; 1260 | export function createWriteStream(path: string, options?: { 1261 | flags?: string; 1262 | encoding?: string; 1263 | string?: string; 1264 | }): WriteStream; 1265 | } 1266 | 1267 | declare module "path" { 1268 | 1269 | /** 1270 | * A parsed path object generated by path.parse() or consumed by path.format(). 1271 | */ 1272 | export interface ParsedPath { 1273 | /** 1274 | * The root of the path such as '/' or 'c:\' 1275 | */ 1276 | root: string; 1277 | /** 1278 | * The full directory path such as '/home/user/dir' or 'c:\path\dir' 1279 | */ 1280 | dir: string; 1281 | /** 1282 | * The file name including extension (if any) such as 'index.html' 1283 | */ 1284 | base: string; 1285 | /** 1286 | * The file extension (if any) such as '.html' 1287 | */ 1288 | ext: string; 1289 | /** 1290 | * The file name without extension (if any) such as 'index' 1291 | */ 1292 | name: string; 1293 | } 1294 | 1295 | /** 1296 | * Normalize a string path, reducing '..' and '.' parts. 1297 | * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. 1298 | * 1299 | * @param p string path to normalize. 1300 | */ 1301 | export function normalize(p: string): string; 1302 | /** 1303 | * Join all arguments together and normalize the resulting path. 1304 | * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. 1305 | * 1306 | * @param paths string paths to join. 1307 | */ 1308 | export function join(...paths: any[]): string; 1309 | /** 1310 | * Join all arguments together and normalize the resulting path. 1311 | * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. 1312 | * 1313 | * @param paths string paths to join. 1314 | */ 1315 | export function join(...paths: string[]): string; 1316 | /** 1317 | * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. 1318 | * 1319 | * Starting from leftmost {from} paramter, resolves {to} to an absolute path. 1320 | * 1321 | * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. 1322 | * 1323 | * @param pathSegments string paths to join. Non-string arguments are ignored. 1324 | */ 1325 | export function resolve(...pathSegments: any[]): string; 1326 | /** 1327 | * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. 1328 | * 1329 | * @param path path to test. 1330 | */ 1331 | export function isAbsolute(path: string): boolean; 1332 | /** 1333 | * Solve the relative path from {from} to {to}. 1334 | * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. 1335 | * 1336 | * @param from 1337 | * @param to 1338 | */ 1339 | export function relative(from: string, to: string): string; 1340 | /** 1341 | * Return the directory name of a path. Similar to the Unix dirname command. 1342 | * 1343 | * @param p the path to evaluate. 1344 | */ 1345 | export function dirname(p: string): string; 1346 | /** 1347 | * Return the last portion of a path. Similar to the Unix basename command. 1348 | * Often used to extract the file name from a fully qualified path. 1349 | * 1350 | * @param p the path to evaluate. 1351 | * @param ext optionally, an extension to remove from the result. 1352 | */ 1353 | export function basename(p: string, ext?: string): string; 1354 | /** 1355 | * Return the extension of the path, from the last '.' to end of string in the last portion of the path. 1356 | * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string 1357 | * 1358 | * @param p the path to evaluate. 1359 | */ 1360 | export function extname(p: string): string; 1361 | /** 1362 | * The platform-specific file separator. '\\' or '/'. 1363 | */ 1364 | export var sep: string; 1365 | /** 1366 | * The platform-specific file delimiter. ';' or ':'. 1367 | */ 1368 | export var delimiter: string; 1369 | /** 1370 | * Returns an object from a path string - the opposite of format(). 1371 | * 1372 | * @param pathString path to evaluate. 1373 | */ 1374 | export function parse(pathString: string): ParsedPath; 1375 | /** 1376 | * Returns a path string from an object - the opposite of parse(). 1377 | * 1378 | * @param pathString path to evaluate. 1379 | */ 1380 | export function format(pathObject: ParsedPath): string; 1381 | 1382 | export module posix { 1383 | export function normalize(p: string): string; 1384 | export function join(...paths: any[]): string; 1385 | export function resolve(...pathSegments: any[]): string; 1386 | export function isAbsolute(p: string): boolean; 1387 | export function relative(from: string, to: string): string; 1388 | export function dirname(p: string): string; 1389 | export function basename(p: string, ext?: string): string; 1390 | export function extname(p: string): string; 1391 | export var sep: string; 1392 | export var delimiter: string; 1393 | export function parse(p: string): ParsedPath; 1394 | export function format(pP: ParsedPath): string; 1395 | } 1396 | 1397 | export module win32 { 1398 | export function normalize(p: string): string; 1399 | export function join(...paths: any[]): string; 1400 | export function resolve(...pathSegments: any[]): string; 1401 | export function isAbsolute(p: string): boolean; 1402 | export function relative(from: string, to: string): string; 1403 | export function dirname(p: string): string; 1404 | export function basename(p: string, ext?: string): string; 1405 | export function extname(p: string): string; 1406 | export var sep: string; 1407 | export var delimiter: string; 1408 | export function parse(p: string): ParsedPath; 1409 | export function format(pP: ParsedPath): string; 1410 | } 1411 | } 1412 | 1413 | declare module "string_decoder" { 1414 | export interface NodeStringDecoder { 1415 | write(buffer: Buffer): string; 1416 | detectIncompleteChar(buffer: Buffer): number; 1417 | } 1418 | export var StringDecoder: { 1419 | new (encoding: string): NodeStringDecoder; 1420 | }; 1421 | } 1422 | 1423 | declare module "tls" { 1424 | import crypto = require("crypto"); 1425 | import net = require("net"); 1426 | import stream = require("stream"); 1427 | 1428 | var CLIENT_RENEG_LIMIT: number; 1429 | var CLIENT_RENEG_WINDOW: number; 1430 | 1431 | export interface TlsOptions { 1432 | pfx?: any; //string or buffer 1433 | key?: any; //string or buffer 1434 | passphrase?: string; 1435 | cert?: any; 1436 | ca?: any; //string or buffer 1437 | crl?: any; //string or string array 1438 | ciphers?: string; 1439 | honorCipherOrder?: any; 1440 | requestCert?: boolean; 1441 | rejectUnauthorized?: boolean; 1442 | NPNProtocols?: any; //array or Buffer; 1443 | SNICallback?: (servername: string) => any; 1444 | } 1445 | 1446 | export interface ConnectionOptions { 1447 | host?: string; 1448 | port?: number; 1449 | socket?: net.Socket; 1450 | pfx?: any; //string | Buffer 1451 | key?: any; //string | Buffer 1452 | passphrase?: string; 1453 | cert?: any; //string | Buffer 1454 | ca?: any; //Array of string | Buffer 1455 | rejectUnauthorized?: boolean; 1456 | NPNProtocols?: any; //Array of string | Buffer 1457 | servername?: string; 1458 | } 1459 | 1460 | export interface Server extends net.Server { 1461 | // Extended base methods 1462 | listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server; 1463 | listen(path: string, listeningListener?: Function): Server; 1464 | listen(handle: any, listeningListener?: Function): Server; 1465 | 1466 | listen(port: number, host?: string, callback?: Function): Server; 1467 | close(): Server; 1468 | address(): { port: number; family: string; address: string; }; 1469 | addContext(hostName: string, credentials: { 1470 | key: string; 1471 | cert: string; 1472 | ca: string; 1473 | }): void; 1474 | maxConnections: number; 1475 | connections: number; 1476 | } 1477 | 1478 | export interface ClearTextStream extends stream.Duplex { 1479 | authorized: boolean; 1480 | authorizationError: Error; 1481 | getPeerCertificate(): any; 1482 | getCipher: { 1483 | name: string; 1484 | version: string; 1485 | }; 1486 | address: { 1487 | port: number; 1488 | family: string; 1489 | address: string; 1490 | }; 1491 | remoteAddress: string; 1492 | remotePort: number; 1493 | } 1494 | 1495 | export interface SecurePair { 1496 | encrypted: any; 1497 | cleartext: any; 1498 | } 1499 | 1500 | export interface SecureContextOptions { 1501 | pfx?: any; //string | buffer 1502 | key?: any; //string | buffer 1503 | passphrase?: string; 1504 | cert?: any; // string | buffer 1505 | ca?: any; // string | buffer 1506 | crl?: any; // string | string[] 1507 | ciphers?: string; 1508 | honorCipherOrder?: boolean; 1509 | } 1510 | 1511 | export interface SecureContext { 1512 | context: any; 1513 | } 1514 | 1515 | export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) =>void ): Server; 1516 | export function connect(options: TlsOptions, secureConnectionListener?: () =>void ): ClearTextStream; 1517 | export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; 1518 | export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; 1519 | export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; 1520 | export function createSecureContext(details: SecureContextOptions): SecureContext; 1521 | } 1522 | 1523 | declare module "crypto" { 1524 | export interface CredentialDetails { 1525 | pfx: string; 1526 | key: string; 1527 | passphrase: string; 1528 | cert: string; 1529 | ca: any; //string | string array 1530 | crl: any; //string | string array 1531 | ciphers: string; 1532 | } 1533 | export interface Credentials { context?: any; } 1534 | export function createCredentials(details: CredentialDetails): Credentials; 1535 | export function createHash(algorithm: string): Hash; 1536 | export function createHmac(algorithm: string, key: string): Hmac; 1537 | export function createHmac(algorithm: string, key: Buffer): Hmac; 1538 | interface Hash { 1539 | update(data: any, input_encoding?: string): Hash; 1540 | digest(encoding: 'buffer'): Buffer; 1541 | digest(encoding: string): any; 1542 | digest(): Buffer; 1543 | } 1544 | interface Hmac { 1545 | update(data: any, input_encoding?: string): Hmac; 1546 | digest(encoding: 'buffer'): Buffer; 1547 | digest(encoding: string): any; 1548 | digest(): Buffer; 1549 | } 1550 | export function createCipher(algorithm: string, password: any): Cipher; 1551 | export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; 1552 | interface Cipher { 1553 | update(data: Buffer): Buffer; 1554 | update(data: string, input_encoding?: string, output_encoding?: string): string; 1555 | final(): Buffer; 1556 | final(output_encoding: string): string; 1557 | setAutoPadding(auto_padding: boolean): void; 1558 | } 1559 | export function createDecipher(algorithm: string, password: any): Decipher; 1560 | export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; 1561 | interface Decipher { 1562 | update(data: Buffer): Buffer; 1563 | update(data: string, input_encoding?: string, output_encoding?: string): string; 1564 | final(): Buffer; 1565 | final(output_encoding: string): string; 1566 | setAutoPadding(auto_padding: boolean): void; 1567 | } 1568 | export function createSign(algorithm: string): Signer; 1569 | interface Signer { 1570 | update(data: any): void; 1571 | sign(private_key: string, output_format: string): string; 1572 | } 1573 | export function createVerify(algorith: string): Verify; 1574 | interface Verify { 1575 | update(data: any): void; 1576 | verify(object: string, signature: string, signature_format?: string): boolean; 1577 | } 1578 | export function createDiffieHellman(prime_length: number): DiffieHellman; 1579 | export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman; 1580 | interface DiffieHellman { 1581 | generateKeys(encoding?: string): string; 1582 | computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; 1583 | getPrime(encoding?: string): string; 1584 | getGenerator(encoding: string): string; 1585 | getPublicKey(encoding?: string): string; 1586 | getPrivateKey(encoding?: string): string; 1587 | setPublicKey(public_key: string, encoding?: string): void; 1588 | setPrivateKey(public_key: string, encoding?: string): void; 1589 | } 1590 | export function getDiffieHellman(group_name: string): DiffieHellman; 1591 | export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; 1592 | export function pbkdf2Sync(password: string, salt: string, iterations: number, keylen: number) : Buffer; 1593 | export function randomBytes(size: number): Buffer; 1594 | export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; 1595 | export function pseudoRandomBytes(size: number): Buffer; 1596 | export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; 1597 | } 1598 | 1599 | declare module "stream" { 1600 | import events = require("events"); 1601 | 1602 | export interface Stream extends events.EventEmitter { 1603 | pipe(destination: T, options?: { end?: boolean; }): T; 1604 | } 1605 | 1606 | export interface ReadableOptions { 1607 | highWaterMark?: number; 1608 | encoding?: string; 1609 | objectMode?: boolean; 1610 | } 1611 | 1612 | export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { 1613 | readable: boolean; 1614 | constructor(opts?: ReadableOptions); 1615 | _read(size: number): void; 1616 | read(size?: number): string|Buffer; 1617 | setEncoding(encoding: string): void; 1618 | pause(): void; 1619 | resume(): void; 1620 | pipe(destination: T, options?: { end?: boolean; }): T; 1621 | unpipe(destination?: T): void; 1622 | unshift(chunk: string): void; 1623 | unshift(chunk: Buffer): void; 1624 | wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; 1625 | push(chunk: any, encoding?: string): boolean; 1626 | } 1627 | 1628 | export interface WritableOptions { 1629 | highWaterMark?: number; 1630 | decodeStrings?: boolean; 1631 | } 1632 | 1633 | export class Writable extends events.EventEmitter implements NodeJS.WritableStream { 1634 | writable: boolean; 1635 | constructor(opts?: WritableOptions); 1636 | _write(data: Buffer, encoding: string, callback: Function): void; 1637 | _write(data: string, encoding: string, callback: Function): void; 1638 | write(buffer: Buffer, cb?: Function): boolean; 1639 | write(str: string, cb?: Function): boolean; 1640 | write(str: string, encoding?: string, cb?: Function): boolean; 1641 | end(): void; 1642 | end(buffer: Buffer, cb?: Function): void; 1643 | end(str: string, cb?: Function): void; 1644 | end(str: string, encoding?: string, cb?: Function): void; 1645 | } 1646 | 1647 | export interface DuplexOptions extends ReadableOptions, WritableOptions { 1648 | allowHalfOpen?: boolean; 1649 | } 1650 | 1651 | // Note: Duplex extends both Readable and Writable. 1652 | export class Duplex extends Readable implements NodeJS.ReadWriteStream { 1653 | writable: boolean; 1654 | constructor(opts?: DuplexOptions); 1655 | _write(data: Buffer, encoding: string, callback: Function): void; 1656 | _write(data: string, encoding: string, callback: Function): void; 1657 | write(buffer: Buffer, cb?: Function): boolean; 1658 | write(str: string, cb?: Function): boolean; 1659 | write(str: string, encoding?: string, cb?: Function): boolean; 1660 | end(): void; 1661 | end(buffer: Buffer, cb?: Function): void; 1662 | end(str: string, cb?: Function): void; 1663 | end(str: string, encoding?: string, cb?: Function): void; 1664 | } 1665 | 1666 | export interface TransformOptions extends ReadableOptions, WritableOptions {} 1667 | 1668 | // Note: Transform lacks the _read and _write methods of Readable/Writable. 1669 | export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { 1670 | readable: boolean; 1671 | writable: boolean; 1672 | constructor(opts?: TransformOptions); 1673 | _transform(chunk: Buffer, encoding: string, callback: Function): void; 1674 | _transform(chunk: string, encoding: string, callback: Function): void; 1675 | _flush(callback: Function): void; 1676 | read(size?: number): any; 1677 | setEncoding(encoding: string): void; 1678 | pause(): void; 1679 | resume(): void; 1680 | pipe(destination: T, options?: { end?: boolean; }): T; 1681 | unpipe(destination?: T): void; 1682 | unshift(chunk: string): void; 1683 | unshift(chunk: Buffer): void; 1684 | wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; 1685 | push(chunk: any, encoding?: string): boolean; 1686 | write(buffer: Buffer, cb?: Function): boolean; 1687 | write(str: string, cb?: Function): boolean; 1688 | write(str: string, encoding?: string, cb?: Function): boolean; 1689 | end(): void; 1690 | end(buffer: Buffer, cb?: Function): void; 1691 | end(str: string, cb?: Function): void; 1692 | end(str: string, encoding?: string, cb?: Function): void; 1693 | } 1694 | 1695 | export class PassThrough extends Transform {} 1696 | } 1697 | 1698 | declare module "util" { 1699 | export interface InspectOptions { 1700 | showHidden?: boolean; 1701 | depth?: number; 1702 | colors?: boolean; 1703 | customInspect?: boolean; 1704 | } 1705 | 1706 | export function format(format: any, ...param: any[]): string; 1707 | export function debug(string: string): void; 1708 | export function error(...param: any[]): void; 1709 | export function puts(...param: any[]): void; 1710 | export function print(...param: any[]): void; 1711 | export function log(string: string): void; 1712 | export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string; 1713 | export function inspect(object: any, options: InspectOptions): string; 1714 | export function isArray(object: any): boolean; 1715 | export function isRegExp(object: any): boolean; 1716 | export function isDate(object: any): boolean; 1717 | export function isError(object: any): boolean; 1718 | export function inherits(constructor: any, superConstructor: any): void; 1719 | } 1720 | 1721 | declare module "assert" { 1722 | function internal (value: any, message?: string): void; 1723 | module internal { 1724 | export class AssertionError implements Error { 1725 | name: string; 1726 | message: string; 1727 | actual: any; 1728 | expected: any; 1729 | operator: string; 1730 | generatedMessage: boolean; 1731 | 1732 | constructor(options?: {message?: string; actual?: any; expected?: any; 1733 | operator?: string; stackStartFunction?: Function}); 1734 | } 1735 | 1736 | export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; 1737 | export function ok(value: any, message?: string): void; 1738 | export function equal(actual: any, expected: any, message?: string): void; 1739 | export function notEqual(actual: any, expected: any, message?: string): void; 1740 | export function deepEqual(actual: any, expected: any, message?: string): void; 1741 | export function notDeepEqual(acutal: any, expected: any, message?: string): void; 1742 | export function strictEqual(actual: any, expected: any, message?: string): void; 1743 | export function notStrictEqual(actual: any, expected: any, message?: string): void; 1744 | export var throws: { 1745 | (block: Function, message?: string): void; 1746 | (block: Function, error: Function, message?: string): void; 1747 | (block: Function, error: RegExp, message?: string): void; 1748 | (block: Function, error: (err: any) => boolean, message?: string): void; 1749 | }; 1750 | 1751 | export var doesNotThrow: { 1752 | (block: Function, message?: string): void; 1753 | (block: Function, error: Function, message?: string): void; 1754 | (block: Function, error: RegExp, message?: string): void; 1755 | (block: Function, error: (err: any) => boolean, message?: string): void; 1756 | }; 1757 | 1758 | export function ifError(value: any): void; 1759 | } 1760 | 1761 | export = internal; 1762 | } 1763 | 1764 | declare module "tty" { 1765 | import net = require("net"); 1766 | 1767 | export function isatty(fd: number): boolean; 1768 | export interface ReadStream extends net.Socket { 1769 | isRaw: boolean; 1770 | setRawMode(mode: boolean): void; 1771 | } 1772 | export interface WriteStream extends net.Socket { 1773 | columns: number; 1774 | rows: number; 1775 | } 1776 | } 1777 | 1778 | declare module "domain" { 1779 | import events = require("events"); 1780 | 1781 | export class Domain extends events.EventEmitter { 1782 | run(fn: Function): void; 1783 | add(emitter: events.EventEmitter): void; 1784 | remove(emitter: events.EventEmitter): void; 1785 | bind(cb: (err: Error, data: any) => any): any; 1786 | intercept(cb: (data: any) => any): any; 1787 | dispose(): void; 1788 | 1789 | addListener(event: string, listener: Function): Domain; 1790 | on(event: string, listener: Function): Domain; 1791 | once(event: string, listener: Function): Domain; 1792 | removeListener(event: string, listener: Function): Domain; 1793 | removeAllListeners(event?: string): Domain; 1794 | } 1795 | 1796 | export function create(): Domain; 1797 | } 1798 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "gulp-env", 3 | "version": "0.4.0", 4 | "description": "Add env vars to your process.env", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "mocha test/*.js" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git://github.com/moveline/gulp-env.git" 12 | }, 13 | "keywords": [ 14 | "gulp", 15 | "gulp-env", 16 | "env", 17 | "process.env", 18 | "gulpfriendly" 19 | ], 20 | "contributors": [ 21 | "Moveline", 22 | "Isiah Meadows (https://github.com/impinball)" 23 | ], 24 | "license": "MIT", 25 | "bugs": { 26 | "url": "https://github.com/moveline/gulp-env/issues" 27 | }, 28 | "homepage": "https://github.com/moveline/gulp-env", 29 | "devDependencies": { 30 | "chai": "^1.9.1", 31 | "gulp": "^3.9.0", 32 | "mocha": "^1.21.4" 33 | }, 34 | "typescript": { 35 | "definition": "./gulp-env.d.ts" 36 | }, 37 | "dependencies": { 38 | "ini": "^1.3.4", 39 | "through2": "^2.0.0" 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /test/mock-env-ini.ini: -------------------------------------------------------------------------------- 1 | STARK = "direwolf" 2 | BARATHEON = "stag" 3 | LANNISTER = "lion" 4 | -------------------------------------------------------------------------------- /test/mock-env-json.json: -------------------------------------------------------------------------------- 1 | { 2 | "STARK": "direwolf", 3 | "BARATHEON": "stag", 4 | "LANNISTER": "lion" 5 | } 6 | -------------------------------------------------------------------------------- /test/mock-env-json.txt: -------------------------------------------------------------------------------- 1 | { 2 | "STARK": "direwolf", 3 | "BARATHEON": "stag", 4 | "LANNISTER": "lion" 5 | } 6 | -------------------------------------------------------------------------------- /test/mock-env-module.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | STARK: "direwolf", 3 | BARATHEON: "stag", 4 | LANNISTER: "lion", 5 | } 6 | -------------------------------------------------------------------------------- /test/mock-env-txt.txt: -------------------------------------------------------------------------------- 1 | foobar 2 | -------------------------------------------------------------------------------- /test/test-gulp-env.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var env = require('../'); 4 | var expect = require('chai').expect; 5 | var fs = require('fs'); 6 | var resolve = require('path').resolve; 7 | var gulp = require('gulp'); 8 | var through2 = require('through2'); 9 | 10 | describe('gulp-env', function() { 11 | function prepVars() { 12 | delete process.env.STARK; 13 | delete process.env.BARATHEON; 14 | delete process.env.LANNISTER; 15 | } 16 | 17 | it('should exist', function() { 18 | expect(env).to.exist; 19 | }); 20 | 21 | describe('reads properties from files', function() { 22 | beforeEach(prepVars); 23 | afterEach(prepVars); 24 | 25 | it('should add process.env vars from a local module', function() { 26 | expect(process.env.STARK).not.to.exist 27 | expect(process.env.BARATHEON).not.to.exist 28 | expect(process.env.LANNISTER).not.to.exist 29 | 30 | env({file: "test/mock-env-module"}) 31 | 32 | expect(process.env.STARK).to.equal("direwolf"); 33 | expect(process.env.BARATHEON).to.equal("stag"); 34 | expect(process.env.LANNISTER).to.equal("lion"); 35 | }); 36 | 37 | it('should take the file as the sole argument as a string', function() { 38 | expect(process.env.STARK).not.to.exist 39 | expect(process.env.BARATHEON).not.to.exist 40 | expect(process.env.LANNISTER).not.to.exist 41 | 42 | env("test/mock-env-module") 43 | 44 | expect(process.env.STARK).to.equal("direwolf"); 45 | expect(process.env.BARATHEON).to.equal("stag"); 46 | expect(process.env.LANNISTER).to.equal("lion"); 47 | }); 48 | 49 | it('should add process.env vars from a local json file', function() { 50 | expect(process.env.STARK).not.to.exist 51 | expect(process.env.BARATHEON).not.to.exist 52 | expect(process.env.LANNISTER).not.to.exist 53 | 54 | env({file: "test/mock-env-json.json"}) 55 | 56 | expect(process.env.STARK).to.equal("direwolf"); 57 | expect(process.env.BARATHEON).to.equal("stag"); 58 | expect(process.env.LANNISTER).to.equal("lion"); 59 | }); 60 | 61 | it('should add process.env vars from a local ini file', function() { 62 | expect(process.env.STARK).not.to.exist 63 | expect(process.env.BARATHEON).not.to.exist 64 | expect(process.env.LANNISTER).not.to.exist 65 | 66 | env({file: "test/mock-env-ini.ini"}) 67 | 68 | expect(process.env.STARK).to.equal("direwolf"); 69 | expect(process.env.BARATHEON).to.equal("stag"); 70 | expect(process.env.LANNISTER).to.equal("lion"); 71 | }); 72 | 73 | it('should treat a file as a different type when given a type', function() { 74 | expect(process.env.STARK).not.to.exist 75 | expect(process.env.BARATHEON).not.to.exist 76 | expect(process.env.LANNISTER).not.to.exist 77 | 78 | env({file: "test/mock-env-json.txt", type: '.json'}) 79 | 80 | expect(process.env.STARK).to.equal("direwolf"); 81 | expect(process.env.BARATHEON).to.equal("stag"); 82 | expect(process.env.LANNISTER).to.equal("lion"); 83 | }); 84 | 85 | it('should throw if the given type is unsupported', function() { 86 | expect(function() { 87 | env({file: "test/mock-env-json.txt", type: '.blarg'}) 88 | }).to.throw(); 89 | }); 90 | 91 | it('should add a missing dot to the type if a type is given', function() { 92 | expect(process.env.STARK).not.to.exist 93 | expect(process.env.BARATHEON).not.to.exist 94 | expect(process.env.LANNISTER).not.to.exist 95 | 96 | env({file: "test/mock-env-json.txt", type: 'json'}) 97 | 98 | expect(process.env.STARK).to.equal("direwolf"); 99 | expect(process.env.BARATHEON).to.equal("stag"); 100 | expect(process.env.LANNISTER).to.equal("lion"); 101 | }); 102 | 103 | it('should throw if the file doesn\'t exist', function() { 104 | expect(function() { 105 | env("test/mock-env-blarg") 106 | }).to.throw(); 107 | }); 108 | }); 109 | 110 | describe('reads vars from vars object', function(){ 111 | afterEach(function() { 112 | delete process.env.NED; 113 | delete process.env.ROBERT; 114 | delete process.env.TYWIN; 115 | }); 116 | 117 | it('should add process.env vars from vars object', function() { 118 | expect(process.env.NED).not.to.exist 119 | expect(process.env.ROBERT).not.to.exist 120 | expect(process.env.TYWIN).not.to.exist 121 | 122 | env({vars: { 123 | NED: true, 124 | ROBERT: 'fat', 125 | TYWIN: 9001 126 | }}) 127 | 128 | expect(process.env.NED).to.equal('true'); 129 | expect(process.env.ROBERT).to.equal('fat'); 130 | expect(process.env.TYWIN).to.equal('9001'); 131 | }); 132 | 133 | it('should add process.env vars in env.set', function() { 134 | expect(process.env.NED).not.to.exist 135 | expect(process.env.ROBERT).not.to.exist 136 | expect(process.env.TYWIN).not.to.exist 137 | 138 | env.set({ 139 | NED: true, 140 | ROBERT: 'fat', 141 | TYWIN: 9001 142 | }); 143 | 144 | expect(process.env.NED).to.equal('true'); 145 | expect(process.env.ROBERT).to.equal('fat'); 146 | expect(process.env.TYWIN).to.equal('9001'); 147 | }); 148 | }); 149 | 150 | describe('reads properties from files and vars object', function() { 151 | beforeEach(prepVars); 152 | afterEach(prepVars); 153 | 154 | it('should overwrite files with inline-vars by default', function() { 155 | expect(process.env.STARK).not.to.exist 156 | 157 | env({ 158 | file: "test/mock-env-json.json", 159 | vars: { 160 | STARK: "wolfenstein" 161 | } 162 | }); 163 | 164 | expect(process.env.STARK).to.equal('wolfenstein') 165 | expect(process.env.BARATHEON).to.equal('stag') 166 | expect(process.env.LANNISTER).to.equal('lion') 167 | }); 168 | }); 169 | 170 | describe('calls and reads the result of handlers', function() { 171 | beforeEach(prepVars); 172 | afterEach(prepVars); 173 | 174 | it('should call the handler with exactly two arguments', function() { 175 | var called = false; 176 | var args; 177 | 178 | env({file: "test/mock-env-txt.txt", handler: function() { 179 | called = true; 180 | args = [].slice.call(arguments); 181 | }}); 182 | 183 | expect(called).to.be.true 184 | expect(args).to.have.length(1); 185 | }); 186 | 187 | it('should pass the contents first', function() { 188 | var expected = fs.readFileSync('test/mock-env-txt.txt', 'utf8'); 189 | 190 | env({file: "test/mock-env-txt.txt", handler: function(found) { 191 | expect(found).to.equal(expected); 192 | }}); 193 | }); 194 | 195 | it('should not be called if the file doesn\'t exist', function() { 196 | var called = false; 197 | 198 | try { 199 | env({file: "test/mock-env-blarg", handler: function() { 200 | called = true 201 | }}); 202 | } catch (e) {} 203 | 204 | expect(called).to.be.false 205 | }); 206 | 207 | it('should add process.env vars from the result of a handler', function() { 208 | expect(process.env.STARK).not.to.exist 209 | expect(process.env.BARATHEON).not.to.exist 210 | expect(process.env.LANNISTER).not.to.exist 211 | 212 | env({file: "test/mock-env-txt.txt", handler: function() { 213 | return { 214 | STARK: "direwolf", 215 | BARATHEON: "stag", 216 | LANNISTER: "lion", 217 | }; 218 | }}); 219 | 220 | expect(process.env.STARK).to.equal("direwolf"); 221 | expect(process.env.BARATHEON).to.equal("stag"); 222 | expect(process.env.LANNISTER).to.equal("lion"); 223 | }); 224 | 225 | it('should be overwritten by inline-vars', function() { 226 | env({ 227 | file: "test/mock-env-txt.txt", 228 | handler: function() { 229 | return { 230 | STARK: "foo", 231 | BARATHEON: "bar", 232 | }; 233 | }, 234 | vars: {STARK: "bar"} 235 | }); 236 | 237 | expect(process.env.STARK).to.equal("bar"); 238 | expect(process.env.BARATHEON).to.equal("bar"); 239 | }); 240 | 241 | it('should return a value that has own property `.restore`', function() { 242 | expect(env.set({})).to.have.ownProperty('restore'); 243 | }); 244 | 245 | it('should return a value with a `.restore` method', function() { 246 | expect(env.set({}).restore).to.be.a('function'); 247 | }); 248 | }); 249 | 250 | describe('`.restore()` on return value', function() { 251 | beforeEach(prepVars); 252 | afterEach(prepVars); 253 | 254 | it('should be able to reset', function() { 255 | var envs = env.set({ 256 | STARK: "direwolf", 257 | BARATHEON: "stag", 258 | LANNISTER: "lion", 259 | }); 260 | expect(process.env.STARK).to.equal("direwolf"); 261 | expect(process.env.BARATHEON).to.equal("stag"); 262 | expect(process.env.LANNISTER).to.equal("lion"); 263 | envs.restore(); 264 | expect(process.env.STARK).to.not.exist; 265 | expect(process.env.BARATHEON).to.not.exist; 266 | expect(process.env.LANNISTER).to.not.exist; 267 | }); 268 | 269 | it('should return true if any keys were restored', function() { 270 | process.env.STARK = "blarg"; 271 | var envs = env.set({ 272 | STARK: "direwolf", 273 | }); 274 | var result = envs.restore(); 275 | expect(process.env.STARK).to.equal("blarg"); 276 | expect(result).to.be.true; 277 | }); 278 | 279 | it('should return false if no keys were restored', function() { 280 | var envs = env.set({ 281 | STARK: "direwolf", 282 | }); 283 | var result = envs.restore(); 284 | expect(process.env.STARK).to.not.exist; 285 | expect(result).to.be.false; 286 | }); 287 | 288 | it('should not attempt to overwrite manually changed keys', function() { 289 | var envs = env.set({ 290 | STARK: "direwolf", 291 | BARATHEON: "stag", 292 | LANNISTER: "lion", 293 | }); 294 | expect(process.env.STARK).to.equal("direwolf"); 295 | expect(process.env.BARATHEON).to.equal("stag"); 296 | expect(process.env.LANNISTER).to.equal("lion"); 297 | process.env.STARK = "nope"; 298 | envs.restore(); 299 | expect(process.env.STARK).to.equal("nope"); 300 | expect(process.env.BARATHEON).to.not.exist; 301 | expect(process.env.LANNISTER).to.not.exist; 302 | }); 303 | 304 | it('should be nestable in scope', function() { 305 | var envs = env.set({ 306 | STARK: "direwolf", 307 | BARATHEON: "stag", 308 | LANNISTER: "lion", 309 | }); 310 | 311 | expect(process.env.STARK).to.equal("direwolf"); 312 | expect(process.env.BARATHEON).to.equal("stag"); 313 | expect(process.env.LANNISTER).to.equal("lion"); 314 | 315 | var next = env.set({ 316 | STARK: "spam", 317 | BARATHEON: "nope", 318 | LANNISTER: "hello", 319 | }); 320 | 321 | expect(process.env.STARK).to.equal("spam"); 322 | expect(process.env.BARATHEON).to.equal("nope"); 323 | expect(process.env.LANNISTER).to.equal("hello"); 324 | 325 | next.restore(); 326 | 327 | expect(process.env.STARK).to.equal("direwolf"); 328 | expect(process.env.BARATHEON).to.equal("stag"); 329 | expect(process.env.LANNISTER).to.equal("lion"); 330 | 331 | envs.restore(); 332 | 333 | expect(process.env.STARK).to.not.exist; 334 | expect(process.env.BARATHEON).to.not.exist; 335 | expect(process.env.LANNISTER).to.not.exist; 336 | }); 337 | 338 | it('should not correct out-of-order restores', function() { 339 | var envs = env.set({ 340 | STARK: "direwolf", 341 | BARATHEON: "stag", 342 | LANNISTER: "lion", 343 | }); 344 | 345 | expect(process.env.STARK).to.equal("direwolf"); 346 | expect(process.env.BARATHEON).to.equal("stag"); 347 | expect(process.env.LANNISTER).to.equal("lion"); 348 | 349 | var next = env.set({ 350 | STARK: "spam", 351 | BARATHEON: "nope", 352 | LANNISTER: "hello", 353 | }); 354 | 355 | expect(process.env.STARK).to.equal("spam"); 356 | expect(process.env.BARATHEON).to.equal("nope"); 357 | expect(process.env.LANNISTER).to.equal("hello"); 358 | 359 | envs.restore(); 360 | 361 | expect(process.env.STARK).to.equal("spam"); 362 | expect(process.env.BARATHEON).to.equal("nope"); 363 | expect(process.env.LANNISTER).to.equal("hello"); 364 | }); 365 | 366 | function testTruthy(item, string) { 367 | it('should ignore conflicts when passed a truthy argument (' + string + 368 | ')', function() { 369 | var envs = env.set({ 370 | STARK: "direwolf", 371 | BARATHEON: "stag", 372 | LANNISTER: "lion", 373 | }); 374 | expect(process.env.STARK).to.equal("direwolf"); 375 | expect(process.env.BARATHEON).to.equal("stag"); 376 | expect(process.env.LANNISTER).to.equal("lion"); 377 | process.env.STARK = "nope"; 378 | envs.restore(true); 379 | expect(process.env.STARK).to.not.exist; 380 | expect(process.env.BARATHEON).to.not.exist; 381 | expect(process.env.LANNISTER).to.not.exist; 382 | }); 383 | } 384 | 385 | testTruthy(1, '1'); 386 | testTruthy({}, '{}'); 387 | testTruthy([], '[]'); 388 | testTruthy(true, 'true'); 389 | }); 390 | 391 | describe('gulp plugin behavior', function() { 392 | beforeEach(prepVars); 393 | afterEach(prepVars); 394 | 395 | it('should work as a gulp plugin', function(done) { 396 | gulp.src('test/mock-env-json.txt') 397 | .pipe(env({ 398 | vars: { 399 | STARK: "direwolf", 400 | BARATHEON: "stag", 401 | LANNISTER: "lion", 402 | }, 403 | })) 404 | .on('end', done) 405 | .on('data', function() {}) 406 | .on('error', done); 407 | }); 408 | 409 | it('should work as a gulp plugin with `.set`', function(done) { 410 | gulp.src('test/mock-env-json.txt') 411 | .pipe(env.set({ 412 | STARK: "direwolf", 413 | BARATHEON: "stag", 414 | LANNISTER: "lion", 415 | })) 416 | .on('end', done) 417 | .on('data', function() {}) 418 | .on('error', done); 419 | }); 420 | 421 | it('should return a value that has own property `.reset`', function() { 422 | expect(env.set({})).to.have.ownProperty('reset'); 423 | }); 424 | 425 | it('should return a value with a `.reset` read/write stream', function() { 426 | var reset = env.set({}).reset; 427 | expect(reset._read).to.be.a('function'); 428 | expect(reset._write).to.be.a('function'); 429 | }); 430 | 431 | it('should be able to reset with `.reset`', function(done) { 432 | var envs = env.set({ 433 | STARK: "direwolf", 434 | BARATHEON: "stag", 435 | LANNISTER: "lion", 436 | }); 437 | gulp.src('test/mock-env-json.txt') 438 | .pipe(envs) 439 | .pipe(through2.obj(function(chunk, enc, callback) { 440 | // Pass through 441 | callback(null, chunk) 442 | }, function(callback) { 443 | try { 444 | expect(process.env.STARK).to.equal("direwolf"); 445 | expect(process.env.BARATHEON).to.equal("stag"); 446 | expect(process.env.LANNISTER).to.equal("lion"); 447 | } catch (e) { 448 | return callback(e); 449 | } 450 | return callback(); 451 | })) 452 | .pipe(envs.reset) 453 | .pipe(through2.obj(function(chunk, enc, callback) { 454 | // Pass through 455 | callback(null, chunk) 456 | }, function(callback) { 457 | try { 458 | expect(process.env.STARK).to.not.exist; 459 | expect(process.env.BARATHEON).to.not.exist; 460 | expect(process.env.LANNISTER).to.not.exist; 461 | } catch (e) { 462 | return callback(e); 463 | } 464 | return callback(); 465 | })) 466 | .on('end', done) 467 | .on('data', function() {}) 468 | .on('error', done); 469 | }); 470 | 471 | it('should not resolve conflicting keys', function(done) { 472 | var envs = env.set({ 473 | STARK: "direwolf", 474 | BARATHEON: "stag", 475 | LANNISTER: "lion", 476 | }); 477 | gulp.src('test/mock-env-json.txt') 478 | .pipe(envs) 479 | .pipe(through2.obj(function(chunk, enc, callback) { 480 | // Pass through 481 | callback(null, chunk) 482 | }, function(callback) { 483 | try { 484 | expect(process.env.STARK).to.equal("direwolf"); 485 | expect(process.env.BARATHEON).to.equal("stag"); 486 | expect(process.env.LANNISTER).to.equal("lion"); 487 | } catch (e) { 488 | return callback(e); 489 | } 490 | process.env.STARK = "blarg"; 491 | return callback(); 492 | })) 493 | .pipe(envs.reset) 494 | .pipe(through2.obj(function(chunk, enc, callback) { 495 | // Pass through 496 | callback(null, chunk) 497 | }, function(callback) { 498 | try { 499 | expect(process.env.STARK).to.equal("blarg"); 500 | expect(process.env.BARATHEON).to.not.exist; 501 | expect(process.env.LANNISTER).to.not.exist; 502 | } catch (e) { 503 | return callback(e); 504 | } 505 | return callback(); 506 | })) 507 | .on('end', done) 508 | .on('data', function() {}) 509 | .on('error', done); 510 | }); 511 | 512 | it('should ignore conflicts when passed as `.force`', function(done) { 513 | var envs = env.set({ 514 | STARK: "direwolf", 515 | BARATHEON: "stag", 516 | LANNISTER: "lion", 517 | }); 518 | gulp.src('test/mock-env-json.txt') 519 | .pipe(envs) 520 | .pipe(through2.obj(function(chunk, enc, callback) { 521 | // Pass through 522 | callback(null, chunk) 523 | }, function(callback) { 524 | try { 525 | expect(process.env.STARK).to.equal("direwolf"); 526 | expect(process.env.BARATHEON).to.equal("stag"); 527 | expect(process.env.LANNISTER).to.equal("lion"); 528 | } catch (e) { 529 | return callback(e); 530 | } 531 | process.env.STARK = "blarg"; 532 | return callback(); 533 | })) 534 | .pipe(envs.reset.force) 535 | .pipe(through2.obj(function(chunk, enc, callback) { 536 | // Pass through 537 | callback(null, chunk) 538 | }, function(callback) { 539 | try { 540 | expect(process.env.STARK).to.not.exist; 541 | expect(process.env.BARATHEON).to.not.exist; 542 | expect(process.env.LANNISTER).to.not.exist; 543 | } catch (e) { 544 | return callback(e); 545 | } 546 | return callback(); 547 | })) 548 | .on('end', done) 549 | .on('data', function() {}) 550 | .on('error', done); 551 | }); 552 | }); 553 | }); 554 | --------------------------------------------------------------------------------