UNPKG

11.3 kBMarkdownView Raw
1# gulp-awspublish
2
3[![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] ![Dependency Status][depstat-image] [![Install size][packagephobia-image]][packagephobia-url]
4
5> awspublish plugin for [gulp](https://github.com/wearefractal/gulp)
6
7## Usage
8
9First, install `gulp-awspublish` as a development dependency:
10
11```shell
12npm install --save-dev gulp-awspublish
13```
14
15Then, add it to your `gulpfile.js`:
16
17```javascript
18var awspublish = require("gulp-awspublish");
19
20gulp.task("publish", function() {
21 // create a new publisher using S3 options
22 // http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#constructor-property
23 var publisher = awspublish.create(
24 {
25 region: "your-region-id",
26 params: {
27 Bucket: "..."
28 }
29 },
30 {
31 cacheFileName: "your-cache-location"
32 }
33 );
34
35 // define custom headers
36 var headers = {
37 "Cache-Control": "max-age=315360000, no-transform, public"
38 // ...
39 };
40
41 return (
42 gulp
43 .src("./public/*.js")
44 // gzip, Set Content-Encoding headers and add .gz extension
45 .pipe(awspublish.gzip({ ext: ".gz" }))
46
47 // publisher will add Content-Length, Content-Type and headers specified above
48 // If not specified it will set x-amz-acl to public-read by default
49 .pipe(publisher.publish(headers))
50
51 // create a cache file to speed up consecutive uploads
52 .pipe(publisher.cache())
53
54 // print upload updates to console
55 .pipe(awspublish.reporter())
56 );
57});
58
59// output
60// [gulp] [create] file1.js.gz
61// [gulp] [create] file2.js.gz
62// [gulp] [update] file3.js.gz
63// [gulp] [cache] file3.js.gz
64// ...
65```
66
67- Note: If you follow the [aws-sdk suggestions](http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html) for
68 providing your credentials you don't need to pass them in to create the publisher.
69
70- Note: In order for publish to work on S3, your policy has to allow the following S3 actions:
71
72```json
73{
74 "Version": "2012-10-17",
75 "Statement": [
76 {
77 "Effect": "Allow",
78 "Action": ["s3:ListBucket"],
79 "Resource": ["arn:aws:s3:::BUCKETNAME"]
80 },
81 {
82 "Effect": "Allow",
83 "Action": [
84 "s3:PutObject",
85 "s3:PutObjectAcl",
86 "s3:GetObject",
87 "s3:GetObjectAcl",
88 "s3:DeleteObject",
89 "s3:ListMultipartUploadParts",
90 "s3:AbortMultipartUpload"
91 ],
92 "Resource": ["arn:aws:s3:::BUCKETNAME/*"]
93 }
94 ]
95}
96```
97
98### Bucket permissions
99
100By default, the plugin works only when public access to the bucket is **not blocked**:
101
102- Block all public access: **Off**
103 - Block public access to buckets and objects granted through new access control lists (ACLs): Off
104 - Block public access to buckets and objects granted through any access control lists (ACLs): Off
105 - Block public access to buckets and objects granted through new public bucket policies: Off
106 - Block public and cross-account access to buckets and objects through any public bucket policies: Off
107
108When dealing with a private bucket, make sure to pass the option `{ noAcl: true }` or a value for the `x-amz-acl` header:
109
110```js
111publisher.publish({}, { noAcl: true });
112publisher.publish({ "x-amz-acl": "something" });
113```
114
115## Testing
116
1171. Create an S3 bucket which will be used for the tests. Optionally create an IAM user for running the tests.
1182. Set the buckets Permission, so it can be edited by the IAM user who will run the tests.
1193. Add an aws-credentials.json file to the project directory with the name of your testing buckets
120 and the credentials of the user who will run the tests.
1214. Run `npm test`
122
123```json
124{
125 "params": {
126 "Bucket": "<test-bucket-name>"
127 },
128 "credentials": {
129 "accessKeyId": "<your-access-key-id>",
130 "secretAccessKey": "<your-secret-access-key>",
131 "signatureVersion": "v3"
132 }
133}
134```
135
136## API
137
138### awspublish.gzip(options)
139
140create a through stream, that gzip file and add Content-Encoding header.
141
142- Note: Node version 0.12.x or later is required in order to use `awspublish.gzip`. If you need an older node engine to work with gzipping, you can use [v2.0.2](https://github.com/pgherveou/gulp-awspublish/tree/v2.0.2).
143
144Available options:
145
146- ext: file extension to add to gzipped file (eg: { ext: '.gz' })
147- smaller: gzip files only when result is smaller
148- Any options that can be passed to [zlib.gzip](https://nodejs.org/api/zlib.html#zlib_options)
149
150### awspublish.create(AWSConfig, cacheOptions)
151
152Create a Publisher.
153The AWSConfig object is used to create an `aws-sdk` S3 client. At a minimum you must pass a `Bucket` key, to define the site bucket. You can find all available options in the [AWS SDK documentation](http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#constructor-property).
154
155The cacheOptions object allows you to define the location of the cached hash digests. By default, they will be saved in your projects root folder in a hidden file called '.awspublish-' + 'name-of-your-bucket'.
156
157#### Adjusting upload timeout
158
159The AWS client has a default timeout which may be too low when pushing large files (> 50mb).
160To adjust timeout, add `httpOptions: { timeout: 300000 }` to the AWSConfig object.
161
162#### Credentials
163
164By default, gulp-awspublish uses the credential chain specified in the AWS [docs](http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html).
165
166Here are some example credential configurations:
167
168Hardcoded credentials (**Note**: We recommend you **not** hard-code credentials inside an application. Use this method only for small personal scripts or for testing purposes.):
169
170```javascript
171var publisher = awspublish.create({
172 region: "your-region-id",
173 params: {
174 Bucket: "..."
175 },
176 credentials: {
177 accessKeyId: "akid",
178 secretAccessKey: "secret"
179 }
180});
181```
182
183Using a profile by name from `~/.aws/credentials`:
184
185```javascript
186var AWS = require("aws-sdk");
187
188var publisher = awspublish.create({
189 region: "your-region-id",
190 params: {
191 Bucket: "..."
192 },
193 credentials: new AWS.SharedIniFileCredentials({ profile: "myprofile" })
194});
195```
196
197Instead of putting anything in the configuration object, you can also provide the following environment variables: `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`, `AWS_PROFILE`. You can also define a `[default]` profile in `~/.aws/credentials` which the SDK will use transparently without needing to set anything.
198
199#### Publisher.publish([headers], [options])
200
201Create a through stream, that push files to s3.
202
203- header: hash of headers to add or override to existing s3 headers.
204- options: optional additional publishing options
205 - force: bypass cache / skip
206 - noAcl: do not set x-amz-acl by default
207 - simulate: debugging option to simulate s3 upload
208 - createOnly: skip file updates
209
210Files that go through the stream receive extra properties:
211
212- s3.path: s3 path
213- s3.etag: file etag
214- s3.date: file last modified date
215- s3.state: publication state (create, update, delete, cache or skip)
216- s3.headers: s3 headers for this file. Defaults headers are:
217 - x-amz-acl: public-read
218 - Content-Type
219 - Content-Length
220
221> Note: `publish` will never delete files remotely. To clean up unused remote files use `sync`.
222
223#### publisher.cache()
224
225Create a through stream that create or update a cache file using file s3 path and file etag.
226Consecutive runs of publish will use this file to avoid reuploading identical files.
227
228Cache file is save in the current working dir and is named `.awspublish-<bucket>`. The cache file is flushed to disk every 10 files just to be safe.
229
230#### Publisher.sync([prefix], [whitelistedFiles])
231
232create a transform stream that delete old files from the bucket.
233
234- prefix: prefix to sync a specific directory
235- whitelistedFiles: array that can contain regular expressions or strings that match against filenames that
236 should never be deleted from the bucket.
237
238e.g.
239
240```js
241// only directory bar will be synced
242// files in folder /foo/bar and file baz.txt will not be removed from the bucket despite not being in your local folder
243gulp
244 .src("./public/*")
245 .pipe(publisher.publish())
246 .pipe(publisher.sync("bar", [/^foo\/bar/, "baz.txt"]))
247 .pipe(awspublish.reporter());
248```
249
250> **warning** `sync` will delete files in your bucket that are not in your local folder unless they're whitelisted.
251
252```js
253// this will publish and sync bucket files with the one in your public directory
254gulp
255 .src("./public/*")
256 .pipe(publisher.publish())
257 .pipe(publisher.sync())
258 .pipe(awspublish.reporter());
259
260// output
261// [gulp] [create] file1.js
262// [gulp] [update] file2.js
263// [gulp] [delete] file3.js
264// ...
265```
266
267#### Publisher.client
268
269The `aws-sdk` S3 client is exposed to let you do other s3 operations.
270
271### awspublish.reporter([options])
272
273Create a reporter that logs s3.path and s3.state (delete, create, update, cache, skip).
274
275Available options:
276
277- states: list of state to log (default to all)
278
279```js
280// this will publish,sync bucket files and print created, updated and deleted files
281gulp
282 .src("./public/*")
283 .pipe(publisher.publish())
284 .pipe(publisher.sync())
285 .pipe(
286 awspublish.reporter({
287 states: ["create", "update", "delete"]
288 })
289 );
290```
291
292## Examples
293
294### [Rename file & directory](examples/rename.js)
295
296You can use `gulp-rename` to rename your files on s3
297
298```js
299// see examples/rename.js
300
301gulp
302 .src("examples/fixtures/*.js")
303 .pipe(
304 rename(function(path) {
305 path.dirname += "/s3-examples";
306 path.basename += "-s3";
307 })
308 )
309 .pipe(publisher.publish())
310 .pipe(awspublish.reporter());
311
312// output
313// [gulp] [create] s3-examples/bar-s3.js
314// [gulp] [create] s3-examples/foo-s3.js
315```
316
317### [Upload file in parallel](examples/concurrent.js)
318
319You can use `concurrent-transform` to upload files in parallel to your amazon bucket
320
321```js
322var parallelize = require("concurrent-transform");
323
324gulp
325 .src("examples/fixtures/*.js")
326 .pipe(parallelize(publisher.publish(), 10))
327 .pipe(awspublish.reporter());
328```
329
330### Upload both gzipped and plain files in one stream
331
332You can use the [`merge-stream`](https://github.com/grncdr/merge-stream) plugin
333to upload two streams in parallel, allowing `sync` to work with mixed file
334types
335
336```js
337var merge = require("merge-stream");
338var gzip = gulp.src("public/**/*.js").pipe(awspublish.gzip());
339var plain = gulp.src(["public/**/*", "!public/**/*.js"]);
340
341merge(gzip, plain)
342 .pipe(publisher.publish())
343 .pipe(publisher.sync())
344 .pipe(awspublish.reporter());
345```
346
347## Plugins
348
349### gulp-awspublish-router
350
351A router for defining file-specific rules
352https://www.npmjs.org/package/gulp-awspublish-router
353
354### gulp-cloudfront-invalidate-aws-publish
355
356Invalidate cloudfront cache based on output from awspublish
357https://www.npmjs.com/package/gulp-cloudfront-invalidate-aws-publish
358
359## License
360
361[MIT License](http://en.wikipedia.org/wiki/MIT_License)
362
363[npm-url]: https://npmjs.org/package/gulp-awspublish
364[npm-image]: https://badge.fury.io/js/gulp-awspublish.svg
365[depstat-image]: https://img.shields.io/librariesio/release/npm/gulp-awspublish?style=flat
366[travis-url]: https://www.travis-ci.org/pgherveou/gulp-awspublish
367[travis-image]: https://www.travis-ci.org/pgherveou/gulp-awspublish.svg?branch=master
368[packagephobia-image]: https://packagephobia.now.sh/badge?p=gulp-awspublish
369[packagephobia-url]: https://packagephobia.now.sh/result?p=gulp-awspublish