Installations
npm install @di-fe/s3
Developer Guide
Typescript
No
Module System
CommonJS
Min. Node Version
>=0.10.20
Node Version
14.20.0
NPM Version
9.1.1
Score
64.5
Supply Chain
97.3
Quality
78.3
Maintenance
25
Vulnerability
98.9
License
Releases
Unable to fetch releases
Contributors
Unable to fetch Contributors
Languages
JavaScript (100%)
Developer
andrewrk
Download Statistics
Total Downloads
855
Last Day
2
Last Week
10
Last Month
14
Last Year
186
GitHub Statistics
1,001 Stars
221 Commits
304 Forks
27 Watching
5 Branches
23 Contributors
Bundle Size
179.58 kB
Minified
51.15 kB
Minified + Gzipped
Package Meta Information
Latest Version
0.0.1
Package Id
@di-fe/s3@0.0.1
Unpacked Size
71.39 kB
Size
16.96 kB
File Count
9
NPM Version
9.1.1
Node Version
14.20.0
Total Downloads
Cumulative downloads
Total Downloads
855
Last day
0%
2
Compared to previous day
Last week
900%
10
Compared to previous week
Last month
250%
14
Compared to previous month
Last year
-53.8%
186
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
High Level Amazon S3 Client
fork from node-s3-client
Installation
npm install s3 --save
Features
- Automatically retry a configurable number of times when S3 returns an error.
- Includes logic to make multiple requests when there is a 1000 object limit.
- Ability to set a limit on the maximum parallelization of S3 requests. Retries get pushed to the end of the parallelization queue.
- Ability to sync a dir to and from S3.
- Progress reporting.
- Supports files of any size (up to S3's maximum 5 TB object size limit).
- Uploads large files quickly using parallel multipart uploads.
- Uses heuristics to compute multipart ETags client-side to avoid uploading or downloading files unnecessarily.
- Automatically provide Content-Type for uploads based on file extension.
- Support third-party S3-compatible platform services like Ceph
See also the companion CLI tool which is meant to be a drop-in replacement for s3cmd: s3-cli.
Synopsis
Create a client
1var s3 = require('s3');
2
3var client = s3.createClient({
4 maxAsyncS3: 20, // this is the default
5 s3RetryCount: 3, // this is the default
6 s3RetryDelay: 1000, // this is the default
7 multipartUploadThreshold: 20971520, // this is the default (20 MB)
8 multipartUploadSize: 15728640, // this is the default (15 MB)
9 s3Options: {
10 accessKeyId: "your s3 key",
11 secretAccessKey: "your s3 secret",
12 region: "your region",
13 // endpoint: 's3.yourdomain.com',
14 // sslEnabled: false
15 // any other options are passed to new AWS.S3()
16 // See: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Config.html#constructor-property
17 },
18});
Create a client from existing AWS.S3 object
1var s3 = require('s3'); 2var awsS3Client = new AWS.S3(s3Options); 3var options = { 4 s3Client: awsS3Client, 5 // more options available. See API docs below. 6}; 7var client = s3.createClient(options);
Upload a file to S3
1var params = { 2 localFile: "some/local/file", 3 4 s3Params: { 5 Bucket: "s3 bucket name", 6 Key: "some/remote/file", 7 // other options supported by putObject, except Body and ContentLength. 8 // See: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObject-property 9 }, 10}; 11var uploader = client.uploadFile(params); 12uploader.on('error', function(err) { 13 console.error("unable to upload:", err.stack); 14}); 15uploader.on('progress', function() { 16 console.log("progress", uploader.progressMd5Amount, 17 uploader.progressAmount, uploader.progressTotal); 18}); 19uploader.on('end', function() { 20 console.log("done uploading"); 21});
Download a file from S3
1var params = { 2 localFile: "some/local/file", 3 4 s3Params: { 5 Bucket: "s3 bucket name", 6 Key: "some/remote/file", 7 // other options supported by getObject 8 // See: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getObject-property 9 }, 10}; 11var downloader = client.downloadFile(params); 12downloader.on('error', function(err) { 13 console.error("unable to download:", err.stack); 14}); 15downloader.on('progress', function() { 16 console.log("progress", downloader.progressAmount, downloader.progressTotal); 17}); 18downloader.on('end', function() { 19 console.log("done downloading"); 20});
Sync a directory to S3
1var params = { 2 localDir: "some/local/dir", 3 deleteRemoved: true, // default false, whether to remove s3 objects 4 // that have no corresponding local file. 5 6 s3Params: { 7 Bucket: "s3 bucket name", 8 Prefix: "some/remote/dir/", 9 // other options supported by putObject, except Body and ContentLength. 10 // See: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObject-property 11 }, 12}; 13var uploader = client.uploadDir(params); 14uploader.on('error', function(err) { 15 console.error("unable to sync:", err.stack); 16}); 17uploader.on('progress', function() { 18 console.log("progress", uploader.progressAmount, uploader.progressTotal); 19}); 20uploader.on('end', function() { 21 console.log("done uploading"); 22});
Tips
-
Consider increasing the socket pool size in the
http
andhttps
global agents. This will improve bandwidth when usinguploadDir
anddownloadDir
functions. For example:1http.globalAgent.maxSockets = https.globalAgent.maxSockets = 20;
API Documentation
s3.AWS
This contains a reference to the aws-sdk module. It is a valid use case to use both this module and the lower level aws-sdk module in tandem.
s3.createClient(options)
Creates an S3 client.
options
:
s3Client
- optional, an instance ofAWS.S3
. Leave blank if you provides3Options
.s3Options
- optional. leave blank if you provides3Client
.- See AWS SDK documentation for available options which are passed to
new AWS.S3()
: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Config.html#constructor-property
- See AWS SDK documentation for available options which are passed to
maxAsyncS3
- maximum number of simultaneous requests this client will ever have open to S3. defaults to20
.s3RetryCount
- how many times to try an S3 operation before giving up. Default 3.s3RetryDelay
- how many milliseconds to wait before retrying an S3 operation. Default 1000.multipartUploadThreshold
- if a file is this many bytes or greater, it will be uploaded via a multipart request. Default is 20MB. Minimum is 5MB. Maximum is 5GB.multipartUploadSize
- when uploading via multipart, this is the part size. The minimum size is 5MB. The maximum size is 5GB. Default is 15MB. Note that S3 has a maximum of 10000 parts for a multipart upload, so if this value is too small, it will be ignored in favor of the minimum necessary value required to upload the file.
s3.getPublicUrl(bucket, key, [bucketLocation])
bucket
S3 bucketkey
S3 keybucketLocation
string, one of these:- "" (default) - US Standard
- "eu-west-1"
- "us-west-1"
- "us-west-2"
- "ap-southeast-1"
- "ap-southeast-2"
- "ap-northeast-1"
- "sa-east-1"
You can find out your bucket location programatically by using this API: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getBucketLocation-property
returns a string which looks like this:
https://s3.amazonaws.com/bucket/key
or maybe this if you are not in US Standard:
https://s3-eu-west-1.amazonaws.com/bucket/key
s3.getPublicUrlHttp(bucket, key)
bucket
S3 Bucketkey
S3 Key
Works for any region, and returns a string which looks like this:
http://bucket.s3.amazonaws.com/key
client.uploadFile(params)
See http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObject-property
params
:
s3Params
: params to pass to AWS SDKputObject
.localFile
: path to the file on disk you want to upload to S3.- (optional)
defaultContentType
: Unless you explicitly set theContentType
parameter ins3Params
, it will be automatically set for you based on the file extension oflocalFile
. If the extension is unrecognized,defaultContentType
will be used instead. Defaults toapplication/octet-stream
.
The difference between using AWS SDK putObject
and this one:
- This works with files, not streams or buffers.
- If the reported MD5 upon upload completion does not match, it retries.
- If the file size is large enough, uses multipart upload to upload parts in parallel.
- Retry based on the client's retry settings.
- Progress reporting.
- Sets the
ContentType
based on file extension if you do not provide it.
Returns an EventEmitter
with these properties:
progressMd5Amount
progressAmount
progressTotal
And these events:
'error' (err)
'end' (data)
- emitted when the file is uploaded successfullydata
is the same object that you get fromputObject
in AWS SDK
'progress'
- emitted whenprogressMd5Amount
,progressAmount
, andprogressTotal
properties change. Note that it is possible for progress to go backwards when an upload fails and must be retried.'fileOpened' (fdSlicer)
- emitted whenlocalFile
has been opened. The file is opened with the fd-slicer module because we might need to read from multiple locations in the file at the same time.fdSlicer
is an object for which you can callcreateReadStream(options)
. See the fd-slicer README for more information.'fileClosed'
- emitted whenlocalFile
has been closed.
And these methods:
abort()
- call this to stop the find operation.
client.downloadFile(params)
See http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getObject-property
params
:
localFile
- the destination path on disk to write the s3 object intos3Params
: params to pass to AWS SDKgetObject
.
The difference between using AWS SDK getObject
and this one:
- This works with a destination file, not a stream or a buffer.
- If the reported MD5 upon download completion does not match, it retries.
- Retry based on the client's retry settings.
- Progress reporting.
Returns an EventEmitter
with these properties:
progressAmount
progressTotal
And these events:
'error' (err)
'end'
- emitted when the file is downloaded successfully'progress'
- emitted whenprogressAmount
andprogressTotal
properties change.
client.downloadBuffer(s3Params)
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getObject-property
s3Params
: params to pass to AWS SDKgetObject
.
The difference between using AWS SDK getObject
and this one:
- This works with a buffer only.
- If the reported MD5 upon download completion does not match, it retries.
- Retry based on the client's retry settings.
- Progress reporting.
Returns an EventEmitter
with these properties:
progressAmount
progressTotal
And these events:
'error' (err)
'end' (buffer)
- emitted when the file is downloaded successfully.buffer
is aBuffer
containing the object data.'progress'
- emitted whenprogressAmount
andprogressTotal
properties change.
client.downloadStream(s3Params)
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getObject-property
s3Params
: params to pass to AWS SDKgetObject
.
The difference between using AWS SDK getObject
and this one:
- This works with a stream only.
If you want retries, progress, or MD5 checking, you must code it yourself.
Returns a ReadableStream
with these additional events:
'httpHeaders' (statusCode, headers)
- contains the HTTP response headers and status code.
client.listObjects(params)
See http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#listObjects-property
params
:
s3Params
- params to pass to AWS SDKlistObjects
.- (optional)
recursive
-true
orfalse
whether or not you want to recurse into directories. Defaultfalse
.
Note that if you set Delimiter
in s3Params
then you will get a list of
objects and folders in the directory you specify. You probably do not want to
set recursive
to true
at the same time as specifying a Delimiter
because
this will cause a request per directory. If you want all objects that share a
prefix, leave the Delimiter
option null
or undefined
.
Be sure that s3Params.Prefix
ends with a trailing slash (/
) unless you
are requesting the top-level listing, in which case s3Params.Prefix
should
be empty string.
The difference between using AWS SDK listObjects
and this one:
- Retries based on the client's retry settings.
- Supports recursive directory listing.
- Makes multiple requests if the number of objects to list is greater than 1000.
Returns an EventEmitter
with these properties:
progressAmount
objectsFound
dirsFound
And these events:
'error' (err)
'end'
- emitted when done listing and no more 'data' events will be emitted.'data' (data)
- emitted when a batch of objects are found. This is the same as thedata
object in AWS SDK.'progress'
- emitted whenprogressAmount
,objectsFound
, anddirsFound
properties change.
And these methods:
abort()
- call this to stop the find operation.
client.deleteObjects(s3Params)
See http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#deleteObjects-property
s3Params
are the same.
The difference between using AWS SDK deleteObjects
and this one:
- Retry based on the client's retry settings.
- Make multiple requests if the number of objects you want to delete is greater than 1000.
Returns an EventEmitter
with these properties:
progressAmount
progressTotal
And these events:
'error' (err)
'end'
- emitted when all objects are deleted.'progress'
- emitted when theprogressAmount
orprogressTotal
properties change.'data' (data)
- emitted when a request completes. There may be more.
client.uploadDir(params)
Syncs an entire directory to S3.
params
:
localDir
- source path on local file system to sync to S3s3Params
Prefix
(required)Bucket
(required)
- (optional)
deleteRemoved
- delete s3 objects with no corresponding local file. default false - (optional)
getS3Params
- function which will be called for every file that needs to be uploaded. You can use this to skip some files. See below. - (optional)
defaultContentType
: Unless you explicitly set theContentType
parameter ins3Params
, it will be automatically set for you based on the file extension oflocalFile
. If the extension is unrecognized,defaultContentType
will be used instead. Defaults toapplication/octet-stream
. - (optional)
followSymlinks
- Set this tofalse
to ignore symlinks. Defaults totrue
.
1function getS3Params(localFile, stat, callback) {
2 // call callback like this:
3 var err = new Error(...); // only if there is an error
4 var s3Params = { // if there is no error
5 ContentType: getMimeType(localFile), // just an example
6 };
7 // pass `null` for `s3Params` if you want to skip uploading this file.
8 callback(err, s3Params);
9}
Returns an EventEmitter
with these properties:
progressAmount
progressTotal
progressMd5Amount
progressMd5Total
deleteAmount
deleteTotal
filesFound
objectsFound
doneFindingFiles
doneFindingObjects
doneMd5
And these events:
'error' (err)
'end'
- emitted when all files are uploaded'progress'
- emitted when any of the above progress properties change.'fileUploadStart' (localFilePath, s3Key)
- emitted when a file begins uploading.'fileUploadEnd' (localFilePath, s3Key)
- emitted when a file successfully finishes uploading.
uploadDir
works like this:
- Start listing all S3 objects for the target
Prefix
. S3 guarantees returned objects to be in sorted order. - Meanwhile, recursively find all files in
localDir
. - Once all local files are found, we sort them (the same way that S3 sorts).
- Next we iterate over the sorted local file list one at a time, computing MD5 sums.
- Now S3 object listing and MD5 sum computing are happening in parallel. As
each operation progresses we compare both sorted lists side-by-side,
iterating over them one at a time, uploading files whose MD5 sums don't
match the remote object (or the remote object is missing), and, if
deleteRemoved
is set, deleting remote objects whose corresponding local files are missing.
client.downloadDir(params)
Syncs an entire directory from S3.
params
:
localDir
- destination directory on local file system to sync tos3Params
Prefix
(required)Bucket
(required)
- (optional)
deleteRemoved
- delete local files with no corresponding s3 object. defaultfalse
- (optional)
getS3Params
- function which will be called for every object that needs to be downloaded. You can use this to skip downloading some objects. See below. - (optional)
followSymlinks
- Set this tofalse
to ignore symlinks. Defaults totrue
.
1function getS3Params(localFile, s3Object, callback) { 2 // localFile is the destination path where the object will be written to 3 // s3Object is same as one element in the `Contents` array from here: 4 // http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#listObjects-property 5 6 // call callback like this: 7 var err = new Error(...); // only if there is an error 8 var s3Params = { // if there is no error 9 VersionId: "abcd", // just an example 10 }; 11 // pass `null` for `s3Params` if you want to skip downloading this object. 12 callback(err, s3Params); 13}
Returns an EventEmitter
with these properties:
progressAmount
progressTotal
progressMd5Amount
progressMd5Total
deleteAmount
deleteTotal
filesFound
objectsFound
doneFindingFiles
doneFindingObjects
doneMd5
And these events:
'error' (err)
'end'
- emitted when all files are downloaded'progress'
- emitted when any of the progress properties above change'fileDownloadStart' (localFilePath, s3Key)
- emitted when a file begins downloading.'fileDownloadEnd' (localFilePath, s3Key)
- emitted when a file successfully finishes downloading.
downloadDir
works like this:
- Start listing all S3 objects for the target
Prefix
. S3 guarantees returned objects to be in sorted order. - Meanwhile, recursively find all files in
localDir
. - Once all local files are found, we sort them (the same way that S3 sorts).
- Next we iterate over the sorted local file list one at a time, computing MD5 sums.
- Now S3 object listing and MD5 sum computing are happening in parallel. As
each operation progresses we compare both sorted lists side-by-side,
iterating over them one at a time, downloading objects whose MD5 sums don't
match the local file (or the local file is missing), and, if
deleteRemoved
is set, deleting local files whose corresponding objects are missing.
client.deleteDir(s3Params)
Deletes an entire directory on S3.
s3Params
:
Bucket
Prefix
- (optional)
MFA
Returns an EventEmitter
with these properties:
progressAmount
progressTotal
And these events:
'error' (err)
'end'
- emitted when all objects are deleted.'progress'
- emitted when theprogressAmount
orprogressTotal
properties change.
deleteDir
works like this:
- Start listing all objects in a bucket recursively. S3 returns 1000 objects per response.
- For each response that comes back with a list of objects in the bucket, immediately send a delete request for all of them.
client.copyObject(s3Params)
See http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#copyObject-property
s3Params
are the same. Don't forget that CopySource
must contain the
source bucket name as well as the source key name.
The difference between using AWS SDK copyObject
and this one:
- Retry based on the client's retry settings.
Returns an EventEmitter
with these events:
'error' (err)
'end' (data)
client.moveObject(s3Params)
See http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#copyObject-property
s3Params
are the same. Don't forget that CopySource
must contain the
source bucket name as well as the source key name.
Under the hood, this uses copyObject
and then deleteObjects
only if the
copy succeeded.
Returns an EventEmitter
with these events:
'error' (err)
'copySuccess' (data)
'end' (data)
Examples
Check if a file exists in S3
Using the AWS SDK, you can send a HEAD request, which will tell you if a file exists at Key
.
See http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#headObject-property
1var client = require('s3').createClient({ /* options */ });
2client.s3.headObject({
3 Bucket: 's3 bucket name',
4 Key: 'some/remote/file'
5}, function(err, data) {
6 if (err) {
7 // file does not exist (err.statusCode == 404)
8 return;
9 }
10 // file exists
11});
Testing
S3_KEY=<valid_s3_key> S3_SECRET=<valid_s3_secret> S3_BUCKET=<valid_s3_bucket> npm test
Tests upload and download large amounts of data to and from S3. The test timeout is set to 40 seconds because Internet connectivity waries wildly.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
Found 11/19 approved changesets -- score normalized to 5
Reason
project is archived
Details
- Warn: Repository is archived.
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 24 are checked with a SAST tool
Score
3.7
/10
Last Scanned on 2024-12-23
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More