• Stars
    star
    1,738
  • Rank 26,795 (Top 0.6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 14 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

S3 Lib

knox

Node Amazon S3 Client.

Features

  • Familiar API (client.get(), client.put(), etc.)
  • Very Node-like low-level request capabilities via http.Client
  • Higher-level API with client.putStream(), client.getFile(), etc.
  • Copying and multi-file delete support
  • Streaming file upload and direct stream-piping support

Examples

The following examples demonstrate some capabilities of knox and the S3 REST API. First things first, create an S3 client:

var client = knox.createClient({
    key: '<api-key-here>'
  , secret: '<secret-here>'
  , bucket: 'learnboost'
});

More options are documented below for features like other endpoints or regions.

PUT

If you want to directly upload some strings to S3, you can use the Client#put method with a string or buffer, just like you would for any http.Client request. You pass in the filename as the first parameter, some headers for the second, and then listen for a 'response' event on the request. Then send the request using req.end(). If we get a 200 response, great!

If you send a string, set Content-Length to the length of the buffer of your string, rather than of the string itself.

var object = { foo: "bar" };
var string = JSON.stringify(object);
var req = client.put('/test/obj.json', {
    'Content-Length': Buffer.byteLength(string)
  , 'Content-Type': 'application/json'
});
req.on('response', function(res){
  if (200 == res.statusCode) {
    console.log('saved to %s', req.url);
  }
});
req.end(string);

By default the x-amz-acl header is private. To alter this simply pass this header to the client request method.

client.put('/test/obj.json', { 'x-amz-acl': 'public-read' });

Each HTTP verb has an alternate method with the "File" suffix, for example put() also has a higher level method named putFile(), accepting a source filename and performing the dirty work shown above for you. Here is an example usage:

client.putFile('my.json', '/user.json', function(err, res){
  // Always either do something with `res` or at least call `res.resume()`.
});

Another alternative is to stream via Client#putStream(), for example:

http.get('http://google.com/doodle.png', function(res){
  var headers = {
      'Content-Length': res.headers['content-length']
    , 'Content-Type': res.headers['content-type']
  };
  client.putStream(res, '/doodle.png', headers, function(err, res){
    // check `err`, then do `res.pipe(..)` or `res.resume()` or whatever.
  });
});

You can also use your stream's pipe method to pipe to the PUT request, but you'll still have to set the 'Content-Length' header. For example:

fs.stat('./Readme.md', function(err, stat){
  // Be sure to handle `err`.

  var req = client.put('/Readme.md', {
      'Content-Length': stat.size
    , 'Content-Type': 'text/plain'
  });

  fs.createReadStream('./Readme.md').pipe(req);

  req.on('response', function(res){
    // ...
  });
});

Finally, if you want a nice interface for putting a buffer or a string of data, use Client#putBuffer():

var buffer = new Buffer('a string of data');
var headers = {
  'Content-Type': 'text/plain'
};
client.putBuffer(buffer, '/string.txt', headers, function(err, res){
  // ...
});

Note that both putFile and putStream will stream to S3 instead of reading into memory, which is great. And they return objects that emit 'progress' events too, so you can monitor how the streaming goes! The progress events have fields written, total, and percent.

GET

Below is an example GET request on the file we just shoved at S3. It simply outputs the response status code, headers, and body.

client.get('/test/Readme.md').on('response', function(res){
  console.log(res.statusCode);
  console.log(res.headers);
  res.setEncoding('utf8');
  res.on('data', function(chunk){
    console.log(chunk);
  });
}).end();

There is also Client#getFile() which uses a callback pattern instead of giving you the raw request:

client.getFile('/test/Readme.md', function(err, res){
  // check `err`, then do `res.pipe(..)` or `res.resume()` or whatever.
});

DELETE

Delete our file:

client.del('/test/Readme.md').on('response', function(res){
  console.log(res.statusCode);
  console.log(res.headers);
}).end();

Likewise we also have Client#deleteFile() as a more concise (yet less flexible) solution:

client.deleteFile('/test/Readme.md', function(err, res){
  // check `err`, then do `res.pipe(..)` or `res.resume()` or whatever.
});

HEAD

As you might expect we have Client#head and Client#headFile, following the same pattern as above.

Advanced Operations

Knox supports a few advanced operations. Like copying files:

client.copy('/test/source.txt', '/test/dest.txt').on('response', function(res){
  console.log(res.statusCode);
  console.log(res.headers);
}).end();

// or

client.copyFile('/source.txt', '/dest.txt', function(err, res){
  // ...
});

even between buckets:

client.copyTo('/source.txt', 'dest-bucket', '/dest.txt').on('response', function(res){
  // ...
}).end();

and even between buckets in different regions:

var destOptions = { region: 'us-west-2', bucket: 'dest-bucket' };
client.copyTo('/source.txt', destOptions, '/dest.txt', function(res){
  // ...
}).end();

or deleting multiple files at once:

client.deleteMultiple(['/test/Readme.md', '/test/Readme.markdown'], function(err, res){
  // ...
});

or listing all the files in your bucket:

client.list({ prefix: 'my-prefix' }, function(err, data){
  /* `data` will look roughly like:

  {
    Prefix: 'my-prefix',
    IsTruncated: true,
    MaxKeys: 1000,
    Contents: [
      {
        Key: 'whatever'
        LastModified: new Date(2012, 11, 25, 0, 0, 0),
        ETag: 'whatever',
        Size: 123,
        Owner: 'you',
        StorageClass: 'whatever'
      },

    ]
  }

  */
});

And you can always issue ad-hoc requests, e.g. the following to get an object's ACL:

client.request('GET', '/test/Readme.md?acl').on('response', function(res){
  // Read and parse the XML response.
  // Everyone loves XML parsing.
}).end();

Finally, you can construct HTTP or HTTPS URLs for a file like so:

var readmeUrl = client.http('/test/Readme.md');
var userDataUrl = client.https('/user.json');

Client Creation Options

Besides the required key, secret, and bucket options, you can supply any of the following:

endpoint

By default knox will send all requests to the global endpoint (s3.amazonaws.com). This works regardless of the region where the bucket is. But if you want to manually set the endpoint, e.g. for performance or testing reasons, or because you are using a S3-compatible service that isn't hosted by Amazon, you can do it with the endpoint option.

region

For your convenience when using buckets not in the US Standard region, you can specify the region option. When you do so, the endpoint is automatically assembled.

As of this writing, valid values for the region option are:

  • US Standard (default): us-standard
  • US West (Oregon): us-west-2
  • US West (Northern California): us-west-1
  • EU (Ireland): eu-west-1
  • Asia Pacific (Singapore): ap-southeast-1
  • Asia Pacific (Tokyo): ap-northeast-1
  • South America (Sao Paulo): sa-east-1

If new regions are added later, their subdomain names will also work when passed as the region option. See the AWS endpoint documentation for the latest list.

Convenience APIs such as putFile and putStream currently do not work as expected with buckets in regions other than US Standard without explicitly specify the region option. This will eventually be addressed by resolving issue #66; however, for performance reasons, it is always best to specify the region option anyway.

secure and port

By default, knox uses HTTPS to connect to S3 on port 443. You can override either of these with the secure and port options. Note that if you specify a custom port option, the default for secure switches to false, although you can override it manually if you want to run HTTPS against a specific port.

token

If you are using the AWS Security Token Service APIs, you can construct the client with a token parameter containing the temporary security credentials token. This simply sets the x-amz-security-token header on every request made by the client.

style

By default, knox tries to use the "virtual hosted style" URLs for accessing S3, e.g. bucket.s3.amazonaws.com. If you pass in "path" as the style option, or pass in a bucket value that cannot be used with virtual hosted style URLs, knox will use "path style" URLs, e.g. s3.amazonaws.com/bucket. There are tradeoffs you should be aware of:

  • Virtual hosted style URLs can work with any region, without requiring it to be explicitly specified; path style URLs cannot.
  • You can access programmatically-created buckets only by using virtual hosted style URLs; path style URLs will not work.
  • You can access buckets with periods in their names over SSL using path style URLs; virtual host style URLs will not work unless you turn off certificate validation.
  • You can access buckets with mixed-case names only using path style URLs; virtual host style URLs will not work.

For more information on the differences between these two types of URLs, and limitations related to them, see the following S3 documentation pages:

agent

Knox disables the default HTTP agent, because it leads to lots of "socket hang up" errors when doing more than 5 requests at once. See #116 for details. If you want to get the default agent back, you can specify agent: require("https").globalAgent, or use your own.

Beyond Knox

Multipart Upload

S3's multipart upload is their rather-complicated way of uploading large files. In particular, it is the only way of streaming files without knowing their Content-Length ahead of time.

Adding the complexity of multipart upload directly to knox is not a great idea. For example, it requires buffering at least 5 MiB of data at a time in memory, which you want to avoid if possible. Fortunately, @nathanoehlman has created the excellent knox-mpu package to let you use multipart upload with knox if you need it!

Easy Download/Upload

@superjoe30 has created a nice library, called simply s3, that makes it very easy to upload local files directly to S3, and download them back to your filesystem. For simple cases this is often exactly what you want!

Uploading With Retries and Exponential Backoff

@jergason created intimidate, a library wrapping Knox to automatically retry failed uploads with exponential backoff. This helps your app deal with intermittent connectivity to S3 without bringing it to a ginding halt.

Listing and Copying Large Buckets

@goodeggs created knox-copy to easily copy and stream keys of buckets beyond Amazon's 1000 key page size limit.

@segmentio created s3-lister to stream a list of bucket keys using the new streams2 interface.

@drob created s3-deleter, a writable stream that batch-deletes bucket keys.

Running Tests

To run the test suite you must first have an S3 account. Then create a file named ./test/auth.json, which contains your credentials as JSON, for example:

{
  "key": "<api-key-here>",
  "secret": "<secret-here>",
  "bucket": "<your-bucket-name>",
  "bucket2": "<another-bucket-name>",
  "bucketUsWest2": "<bucket-in-us-west-2-region-here>"
}

Then install the dev dependencies and execute the test suite:

$ npm install
$ npm test

More Repositories

1

mongoose

MongoDB object modeling designed to work in an asynchronous environment.
JavaScript
26,902
star
2

wp-calypso

The JavaScript and API powered WordPress.com
TypeScript
12,425
star
3

_s

Hi. I'm a starter theme called _s, or underscores, if you like. I'm a theme meant for hacking so don't use me as a Parent Theme. Instead try turning me into the next, most awesome, WordPress theme out there. That's what I'm here for.
CSS
10,933
star
4

node-canvas

Node canvas is a Cairo backed Canvas implementation for NodeJS.
JavaScript
10,079
star
5

kue

Kue is a priority job queue backed by redis, built for node.js.
JavaScript
9,446
star
6

simplenote-electron

Simplenote for Web, Windows, and Linux
TypeScript
4,517
star
7

juice

Juice inlines CSS stylesheets into your HTML source.
JavaScript
3,112
star
8

pocket-casts-android

Pocket Casts Android 🎧
Kotlin
2,537
star
9

cli-table

Pretty unicode tables for the CLI with Node.JS
JavaScript
2,243
star
10

expect.js

Minimalistic BDD-style assertions for Node.JS and the browser.
JavaScript
2,098
star
11

simplenote-ios

Simplenote for iOS
Swift
1,976
star
12

monk

The wise MongoDB API
JavaScript
1,845
star
13

simplenote-android

Simplenote for Android
Java
1,688
star
14

jetpack

Security, performance, marketing, and design tools — Jetpack is made by WordPress experts to make WP sites safer and faster, and help you grow your traffic.
PHP
1,587
star
15

pocket-casts-ios

Pocket Casts iOS app 🎧
Swift
1,464
star
16

simplenote-macos

Simplenote for macOS
Swift
1,420
star
17

antiscroll

OS X Lion style cross-browser native scrolling on the web that gets out of the way.
JavaScript
1,079
star
18

wp-desktop

WordPress.com for Desktop
989
star
19

WP-Job-Manager

Manage job listings from the WordPress admin panel, and allow users to post jobs directly to your site.
PHP
874
star
20

browser-repl

Launch a repl on your command line to any browser in the cloud.
JavaScript
728
star
21

themes

Free WordPress themes made by Automattic for WordPress.org and WordPress.com.
CSS
693
star
22

legalmattic

Democratizing WordPress.com legalese since 2014!
672
star
23

wpcom.js

WordPress.com JavaScript API client designed for Node.js and browsers
JavaScript
658
star
24

Picard

A prototype theme that uses React and WP-API
CSS
631
star
25

fb-instant-articles

Archived (see Readme). Enable Facebook Instant Articles on your WordPress site.
PHP
628
star
26

sensei

Sensei LMS - Online Courses, Quizzes, & Learning
PHP
514
star
27

wordpress-activitypub

ActivityPub for WordPress
PHP
470
star
28

developer

In your WordPress, developing locally
PHP
470
star
29

theme-components

A collection of patterns for creating a custom starter WordPress theme.
PHP
404
star
30

wp-super-cache

WP Super Cache: A fast caching engine for WordPress
PHP
399
star
31

Edit-Flow

WordPress plugin to accelerate your editorial workflow
PHP
341
star
32

o2

The o2 plugin for WordPress — blogging at the speed of thought
JavaScript
332
star
33

newspack-plugin

An advanced open-source publishing and revenue-generating platform for news organizations.
PHP
326
star
34

liveblog

Liveblogging done right. Using WordPress.
PHP
304
star
35

batcache

A memcached HTML page cache for WordPress.
PHP
278
star
36

Co-Authors-Plus

Multiple bylines and Guest Authors for WordPress
PHP
275
star
37

newspack-theme

A theme for Newspack.
PHP
265
star
38

vip-quickstart

Retired
PHP
265
star
39

Iris

A(n awesome) Color Picker
JavaScript
257
star
40

babble

Multilingual WordPress done right.
PHP
245
star
41

syntaxhighlighter

WordPress plugin that makes it easy to post syntax-highlighted code snippets.
CSS
239
star
42

VIP-Coding-Standards

PHP_CodeSniffer ruleset to enforce WordPress VIP coding standards.
PHP
210
star
43

underscores.me

PHP
209
star
44

newspack-blocks

Gutenberg blocks for the Newspack project.
PHP
204
star
45

isolated-block-editor

Repackages Gutenberg's editor playground as a full-featured multi-instance editor that does not require WordPress.
CSS
192
star
46

custom-metadata

A WordPress plugin that provides an easy way to add custom fields to your object types (post, pages, custom post types, users)
PHP
191
star
47

camptix

Moved to https://github.com/WordPress/wordcamp.org/
PHP
182
star
48

woocommerce-payments

Accept payments via credit card. Manage transactions within WordPress.
PHP
173
star
49

browserbuild

JavaScript
170
star
50

vip-go-mu-plugins

The development repo for mu-plugins used on the WordPress VIP Platform.
PHP
158
star
51

Documattic

WordPress presentations and resources shared by WordPress.com VIP
JavaScript
156
star
52

google-docs-add-on

Publish to WordPress from Google Docs
JavaScript
152
star
53

mydb

JavaScript
150
star
54

vip-scanner

Deprecated: Scan all sorts of themes and files and things! Use PHPCS and the VIP coding standards instead
PHP
140
star
55

wp-memcached

Memcached Object Cache for WordPress.
PHP
139
star
56

Genericons

A public mirror of changes to the Genericon release.
CSS
136
star
57

regenerate-thumbnails

WordPress plugin for regenerating thumbnails of uploaded images. Over 1 million active users and counting.
PHP
134
star
58

media-explorer

With Media Explorer, you can now search for tweets and videos on Twitter and YouTube directly from the Add Media screen in WordPress.
PHP
127
star
59

Rewrite-Rules-Inspector

WordPress plugin to inspect your rewrite rules.
PHP
123
star
60

PhpStorm-Resources

PhpStorm is making inroads at Automattic. Here you'll find various helpful files we've made.
123
star
61

wordbless

WorDBless allows you to use WordPress core functions in your PHPUnit tests without having to set up a database and the whole WordPress environment
PHP
122
star
62

Cron-Control

A fresh take on running WordPress's cron system, allowing parallel processing
PHP
121
star
63

vip-go-mu-plugins-built

The generated repo for mu-plugins used on the VIP Go platform.
PHP
120
star
64

social-logos

A repository of all the social logos we use on WordPress.com
JavaScript
119
star
65

ad-code-manager

Easily manage the ad codes that need to appear in your templates
PHP
117
star
66

block-experiments

A monorepo of Block Experiments
JavaScript
114
star
67

genericons-neue

Genericons Neue are generic looking icons, suitable for a blog or simple website
HTML
114
star
68

nginx-http-concat

WordPress plugin to perform CSS and JavaScript concatenation of individual script files into one resource request.
PHP
114
star
69

php-thrift-sql

A PHP library for connecting to Hive or Impala over Thrift
PHP
113
star
70

wp-e2e-tests

Automated end-to-end tests for WordPress.com
JavaScript
112
star
71

gridicons

The WordPress.com icon set
PHP
108
star
72

woocommerce-services

WooCommerce Services is a feature plugin that integrates hosted services into WooCommerce (3.0+), and currently includes automated tax rates and the ability to purchase and print USPS shipping labels.
JavaScript
107
star
73

es-backbone

ElasticSearch Backbone library for quickly building Faceted Search front ends.
JavaScript
103
star
74

syndication

Syndicate your WordPress content.
PHP
102
star
75

theme-tools

Tools for making better themes, better.
JavaScript
99
star
76

phpcs-neutron-standard

A set of phpcs sniffs for PHP >7 development
PHP
94
star
77

mShots

Website Thumbnail/Snapshot Service
JavaScript
94
star
78

prefork

PHP class for pre-loading heavy PHP apps before serving requests
PHP
94
star
79

newspack-newsletters

Author email newsletters in WordPress
PHP
89
star
80

musictheme

A theme for bands and musicians that uses an experimental Gutenberg layout.
CSS
89
star
81

gutenberg-themes-sketch

A set of Sketch files to help you design block-driven WordPress themes.
88
star
82

zoninator

Curation made easy! Create "zones" then add and order your content straight from the WordPress Dashboard.
PHP
85
star
83

cloudup-cli

cloudup command-line executable
JavaScript
83
star
84

go-search-replace

🚀 Search & replace URLs in WordPress SQL files.
Go
81
star
85

measure-builds-gradle-plugin

Gradle Plugin for reporting build time metrics.
Kotlin
81
star
86

lazy-load

Lazy load images on your WordPress site to improve page load times and server bandwidth.
JavaScript
77
star
87

gutenberg-ramp

Control conditions under which Gutenberg loads - either from your theme code or from a UI
PHP
75
star
88

auto-update

Objective-C
73
star
89

wpes-lib

WordPress-Elasticsearch Lib
PHP
73
star
90

vip-go-skeleton

The base repository structure for all VIP Go sites
PHP
72
star
91

jurassic.ninja

A frontend to launching ephemeral WordPress instances that auto-destroy after some time
PHP
70
star
92

msm-sitemap

Comprehensive sitemaps for your WordPress VIP site. Joint collaboration between Metro.co.uk, WordPress VIP, Alley Interactive, Maker Media, 10up, and others.
PHP
70
star
93

vip-go-nextjs-skeleton

A Next.js boilerplate for decoupled WordPress on VIP.
TypeScript
70
star
94

wp-api-console

WordPress (.com and .org) API Console written in React/Redux
JavaScript
69
star
95

gutenberg-block-styles

An example of a simple plugin that adds a block style to Gutenberg.
PHP
68
star
96

atd-chrome

After the Deadline extension for Chrome
JavaScript
66
star
97

eventbrite-api

The Eventbrite API plugin brings the power of Eventbrite to WordPress, for both users and developers.
PHP
65
star
98

mongo-query

mongo query API component
JavaScript
65
star
99

site-logo

Add a logo to your WordPress site. Set it once, and all themes that support it will display it automatically.
PHP
65
star
100

newspack-popups

AMP-compatible popup notifications.
PHP
61
star