S3 GetObject: Read the Body as Text, JSON or a File in AWS SDK v3, boto3, CLI and PowerShell (Fix [object Object] and Stream Errors)
To read a file from Amazon S3 in code, you call GetObject and then read its Body, which is a stream, not text. In the AWS SDK for JavaScript v3: const res = await s3.send(new GetObjectCommand({ Bucket, Key })), then await res.Body.transformToString() for text (or JSON.parse of it), transformToByteArray() for bytes, or pipeline(res.Body, fs.createWriteStream(path)) to save a large file without loading it into memory. Calling res.Body.toString() gives [object Object], the most common v2-to-v3 surprise, because v2 returned a Buffer. In Python boto3: s3.get_object(Bucket=..., Key=...)["Body"].read().decode("utf-8"), or s3.download_file() for files. In the AWS CLI: aws s3 cp s3://bucket/key - to print it, or aws s3api get-object --bucket B --key K out.txt. In PowerShell, Read-S3Object downloads; Get-S3Object only lists. Read the body only once, and always read or discard it, or your app runs out of sockets. Below: working code for each language, JSON, ranges, presigned URLs, TypeScript types, browser use, permissions, and every error.
Jake's first Lambda function had one job: read a price list stored as JSON in S3 and return it. It ran, and returned [object Object]. He had copied the code from an old tutorial written for the previous version of the JavaScript SDK, where the file arrived as a ready-made buffer. In version 3 it arrives as a stream, a pipe the data flows through, and calling toString() on the pipe describes the pipe, not the water. One method call fixed it.
New to S3 or the JavaScript SDK? The cards below cover S3, missing keys, credentials and SDK v3 in ES modules.
Why the Body is a stream, not text
An S3 object can be a 2 KB JSON file or a 50 TB video. If every SDK loaded the whole object into memory before handing it to you, large files would crash your program. So GetObject returns the object's details (size, type, ETag, metadata) at once, and the content as a stream you read when you are ready: all at once for small files, chunk by chunk for big ones. Our plain-English S3 guide covers objects and keys if those are new.
Two rules follow from that, in every language:
- You can read the body once. After you read it to the end, it is empty. Keep the result in a variable if you need it twice.
- You must read it, or discard it. An unread body keeps its network connection open. Do that in a loop and your app runs out of connections and starts waiting or timing out.
Jake: "So the SDK hands me a tap, not a glass of water?"
Ethan: "Right. Turn it on, fill the glass, and don't leave taps running."
The same job in each tool you are likely to use:
| Tool | Read as text | Save to a file | Process big files |
|---|---|---|---|
| JavaScript SDK v3 | await Body.transformToString() | pipeline(Body, createWriteStream(p)) | Pipe through readline or zlib |
| Python boto3 | Body.read().decode("utf-8") | s3.download_file(b, k, p) | Body.iter_lines() / iter_chunks() |
| Java SDK v2 | getObjectAsBytes(req).asUtf8String() | ResponseTransformer.toFile(path) | getObject(req) as an InputStream |
| AWS CLI | aws s3 cp s3://b/k - | aws s3 cp s3://b/k ./file | Pipe aws s3 cp ... - into another command |
| PowerShell | Read-S3Object then Get-Content | Read-S3Object -File path | Download, then read line by line |
JavaScript (AWS SDK v3): text, JSON, bytes, file
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import { createWriteStream } from "node:fs";
import { pipeline } from "node:stream/promises";
const s3 = new S3Client({ region: "us-east-1" });
const res = await s3.send(new GetObjectCommand({ Bucket: "shop-data", Key: "prices.json" }));
// Text
const text = await res.Body.transformToString(); // UTF-8 by default
// JSON
const prices = JSON.parse(text);
// Bytes (Uint8Array), for images, PDFs, zip files
// const bytes = await res.Body.transformToByteArray();
// Save to a file without loading it into memory (use instead of the lines above)
// await pipeline(res.Body, createWriteStream("/tmp/prices.json"));
console.log(res.ContentType, res.ContentLength, prices.length);Pick one of the three ways to read res.Body; each consumes it. transformToString("latin1") takes another encoding if your file is not UTF-8. The response also carries ContentType, ContentLength, ETag, LastModified and Metadata (your custom x-amz-meta-* values) without reading the body.
Coming from SDK v2? The old code looked like this:
// SDK v2 (old): Body was a Buffer, so toString() worked
const data = await s3.getObject({ Bucket, Key }).promise();
const text = data.Body.toString("utf-8");In v3, Body is a stream with the transformTo... helpers, there is no .promise(), and you send command objects. Moving your code over, step by step:
- Install the client you need:
npm install @aws-sdk/client-s3(each service is its own small package). - Create one client per Region and reuse it:
new S3Client({ region }), outside your Lambda handler so it is reused between calls. - Replace each call
s3.getObject(params).promise()withs3.send(new GetObjectCommand(params)). - Replace each body read
data.Body.toString()withawait res.Body.transformToString(). - Update error checks: v3 errors carry
err.name(such as"NoSuchKey") and typed classes you can test withinstanceof, instead of v2'serr.code.
Step 4 alone fixes the most common migration bug, the [object Object] one. In Lambda's Node.js runtimes, v3 is the SDK that is included; our guide to SDK v3 in ES modules covers the import side.
TypeScript: the Body type
In TypeScript, res.Body is typed for both Node.js and browsers, so passing it to Node stream functions needs a hint:
import type { Readable } from "node:stream";
const res = await s3.send(new GetObjectCommand({ Bucket, Key }));
if (!res.Body) throw new Error("empty body");
const text: string = await res.Body.transformToString(); // no cast needed
// For Node stream APIs:
await pipeline(res.Body as Readable, createWriteStream(path));The transformTo... methods need no cast; only Node-specific stream functions do. The if (!res.Body) check is worth keeping: the type allows undefined, and an explicit check gives you a clear error instead of a confusing one later. If your project targets both Node and the browser, keep the S3 reading code in one module and use only the transformTo... helpers there, so it works in both places unchanged.
Jake: "So TypeScript was right to complain?"
Ethan: "It was telling you the same body works in two very different places. You just tell it which one you're in."
Python (boto3): read, decode, stream, download
💻 Where to run these commands
Easiest: AWS CloudShell, nothing to install. Sign in to the AWS Management Console, choose your Region at the top right, then click the CloudShell icon (a small >_ terminal symbol) in the top bar, or type CloudShell in the search box and open it. When the $ prompt appears, paste a command and press Enter. CloudShell already has the AWS CLI, uses your console permissions and costs nothing extra.
On your own computer: install AWS CLI version 2 (installers for Windows, macOS and Linux are on the AWS CLI page), run aws configure once (or aws configure sso if your company signs in through single sign-on), and check it works with aws sts get-caller-identity. Then paste commands into Terminal on Mac or Linux, or PowerShell or Command Prompt on Windows.
Windows tip: a line ending in a backslash ( \ ) continues on the next line in CloudShell, Mac and Linux. In PowerShell use a backtick ( ` ) instead, in Command Prompt a caret ( ^ ), or simply join the lines into one. JSON inside single quotes works as shown in CloudShell; on Windows, save the JSON in a file and pass it as file://name.json.
Python examples: save the code in a file such as script.py, install the AWS SDK with pip install boto3, and run python script.py (python3 on Mac and Linux). It uses the same credentials as the AWS CLI; CloudShell has Python and boto3 ready.
Replace example values such as my-bucket, my-function, 111122223333 (an account ID) and us-east-1 with your own.
import json
import boto3
s3 = boto3.client("s3")
obj = s3.get_object(Bucket="shop-data", Key="prices.json")
# Text and JSON (small files)
text = obj["Body"].read().decode("utf-8")
prices = json.loads(text)
# Line by line, for big text files such as CSV or logs
obj = s3.get_object(Bucket="shop-data", Key="logs/2026-10-19.csv")
for line in obj["Body"].iter_lines():
row = line.decode("utf-8").split(",")
# Straight to a file (handles large objects in parallel parts)
s3.download_file("shop-data", "backups/db-backup.sql.gz", "/tmp/db-backup.sql.gz")
# Into memory as a file-like object
import io
buf = io.BytesIO()
s3.download_fileobj("shop-data", "images/logo.png", buf)Your obj["Body"] is a StreamingBody, the boto3 version of the same tap: read() once, or iterate with iter_lines() or iter_chunks(). For anything bigger than a few hundred MB, download_file is the better choice: it splits the download into parallel ranges and retries parts that fail. Our S3 listing guide shows how to loop over many objects first.
Common formats, straight from the stream. Because obj["Body"] behaves like a file, most Python readers accept it directly, with no temporary file:
import csv, gzip, io
# A gzip-compressed log, decompressed as it streams
obj = s3.get_object(Bucket="shop-data", Key="logs/2026-10-19.log.gz")
with gzip.GzipFile(fileobj=obj["Body"]) as gz:
for line in gz:
handle(line.decode("utf-8"))
# A CSV file, row by row, as dictionaries keyed by the header
obj = s3.get_object(Bucket="shop-data", Key="exports/stock.csv")
rows = csv.DictReader(io.TextIOWrapper(obj["Body"], encoding="utf-8"))
for row in rows:
print(row["sku"], row["qty"])
# pandas, if the file fits comfortably in memory
import pandas as pd
df = pd.read_csv(s3.get_object(Bucket="shop-data", Key="exports/stock.csv")["Body"])pd.read_csv("s3://bucket/key") with a plain S3 path also works, but only after pip install s3fs; passing the boto3 body as above needs nothing extra and uses exactly the credentials your boto3 client has. For JSON Lines files (one JSON object per line), combine iter_lines() with json.loads on each line, which keeps memory flat for files of any size.
Java (AWS SDK for Java 2.x): text, stream, file
Java is where many GetObject searches come from, and the 2.x SDK splits the job into three clear calls. Add the S3 module to your build (Maven artifact software.amazon.awssdk:s3, ideally through the SDK's BOM so all AWS modules share one version), then:
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
S3Client s3 = S3Client.builder().region(Region.US_EAST_1).build();
GetObjectRequest req = GetObjectRequest.builder().bucket("shop-data").key("prices.json").build();
// 1. Small object as text
String json = s3.getObjectAsBytes(req).asUtf8String();
// 2. Big object as a stream, line by line (closes the connection at the end)
try (ResponseInputStream<GetObjectResponse> in = s3.getObject(req);
BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
reader.lines().forEach(System.out::println);
}
// 3. Straight to a file
s3.getObject(req, Paths.get("prices.json"));The try-with-resources block in the second form is the Java version of "always read or close the body": a ResponseInputStream left open holds an HTTP connection, and enough of them exhaust the client's connection pool, after which every call waits and then fails with a timeout acquiring a connection. getObjectAsBytes loads the whole object into memory, so keep it for small files. For very large downloads, the SDK's S3TransferManager splits the object into parallel ranged requests, much like download_file in Python.
Create the S3Client once and reuse it everywhere; building a client per request is slow and leaks resources. In Lambda, create it in a static field or the handler's constructor so warm invocations reuse it.
Moving from Java SDK 1.x: getObjectContent() and S3Object
Older code and tutorials use the 1.x SDK, recognizable by AmazonS3, S3Object and getObjectContent():
// Java SDK 1.x (old)
AmazonS3 s3 = AmazonS3ClientBuilder.defaultClient();
S3Object obj = s3.getObject("shop-data", "prices.json");
try (S3ObjectInputStream in = obj.getObjectContent()) {
// read the stream
}The 1.x SDK entered maintenance mode on July 31, 2024 and reached end-of-support on December 31, 2025, so it receives no fixes, and new S3 features never reach it. Existing 1.x code keeps working, but new code should use 2.x. The mapping is mostly mechanical:
AmazonS3ClientBuilder.defaultClient()becomesS3Client.create()or the builder above.s3.getObject(bucket, key)becomess3.getObject(GetObjectRequest.builder().bucket(...).key(...).build()).obj.getObjectContent()becomes theResponseInputStreamreturned directly bygetObject.obj.getObjectMetadata()becomesin.response(), aGetObjectResponsewithcontentType(),contentLength(),eTag()andmetadata().AmazonS3Exceptionwith status 404 becomesNoSuchKeyException, which you can catch by type.
The JavaScript SDK went through the same change: version 2 reached end-of-support on September 8, 2025, which is why so many Node.js projects are moving to v3 and running into the [object Object] surprise at the top of this page.
Go (AWS SDK for Go v2)
import (
"context"
"io"
"os"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/s3"
)
ctx := context.Background()
cfg, err := config.LoadDefaultConfig(ctx)
if err != nil { panic(err) }
client := s3.NewFromConfig(cfg)
out, err := client.GetObject(ctx, &s3.GetObjectInput{
Bucket: aws.String("shop-data"),
Key: aws.String("prices.json"),
})
if err != nil { panic(err) }
defer out.Body.Close() // always close the body
data, err := io.ReadAll(out.Body) // small objects: all at once
// or, for big ones, copy to a file: f, _ := os.Create("prices.json"); io.Copy(f, out.Body)out.Body is an io.ReadCloser, so every Go tool that reads streams works with it: bufio.Scanner for lines, gzip.NewReader for compressed files, io.Copy to a file. The defer out.Body.Close() line is the Go form of the same rule as everywhere else on this page. A missing key comes back as an error you can test with errors.As(err, &nsk) where nsk is a *types.NoSuchKey.
Pass a context with a deadline (context.WithTimeout) rather than context.Background() in servers, so a stalled download cannot hang a request forever. And as in Java, build the client once at startup and share it: it is safe for concurrent use by many goroutines.
C# and .NET (AWSSDK.S3)
using Amazon.S3;
var client = new AmazonS3Client(); // Region and credentials from your profile or role
// Text
using (var response = await client.GetObjectAsync("shop-data", "prices.json"))
using (var reader = new StreamReader(response.ResponseStream))
{
string json = await reader.ReadToEndAsync();
}
// Straight to a file
using (var response = await client.GetObjectAsync("shop-data", "backups/db.sql.gz"))
{
await response.WriteResponseStreamToFileAsync(@"C:\temp\db.sql.gz", false, CancellationToken.None);
}Install the AWSSDK.S3 NuGet package. The response is IDisposable, and the using blocks are what release the connection, so do not skip them. For large files with parallel parts, TransferUtility in the same package offers DownloadAsync, the .NET counterpart of download_file.
A missing key raises an AmazonS3Exception whose StatusCode is HttpStatusCode.NotFound and whose ErrorCode is NoSuchKey; catch that specifically rather than every exception, so real permission problems still surface. As with every other SDK here, create one client and reuse it, for example by registering it as a singleton in your app's dependency injection.
AWS CLI and PowerShell
# Print an object to the terminal (the "-" means standard output) aws s3 cp s3://shop-data/prices.json - # Download to a file aws s3 cp s3://shop-data/prices.json ./prices.json # Low-level call: the last argument is the file to write (required) aws s3api get-object --bucket shop-data --key prices.json prices.json # Only part of a file aws s3api get-object --bucket shop-data --key big.log --range bytes=0-1023 head.log
aws s3 cp is the high-level command you will use most: it handles large files in parallel parts and shows progress. aws s3api get-object maps one-to-one to the API call, which is useful when you need options such as --range, --version-id or --if-none-match, and it always needs an output file name as its last argument. Printing with - lets you chain commands, for example aws s3 cp s3://shop-data/prices.json - | jq 'first' to look at the first price without saving anything.
In AWS Tools for PowerShell, the names trip people up:
# Download an object to a file Read-S3Object -BucketName shop-data -Key prices.json -File C:\temp\prices.json # Read it as text Get-Content C:\temp\prices.json -Raw | ConvertFrom-Json # Get-S3Object does NOT return content: it lists objects (keys, sizes, dates) Get-S3Object -BucketName shop-data -KeyPrefix invoices/
The naming is the source of a steady stream of confusion: Get-S3Object sounds like GetObject but is really a listing command, while the download is Read-S3Object. For a whole prefix, Read-S3Object -BucketName shop-data -KeyPrefix invoices/ -Folder C:\temp\invoices downloads every object under it into a local folder. The cmdlets come from the AWS.Tools.S3 module (Install-Module AWS.Tools.S3) and use the same profiles as the AWS CLI.
Back in the CLI, two get-object options are worth remembering. --version-id fetches an older version of a file in a versioned bucket, which is how you recover yesterday's copy of a file someone overwrote. And the command prints the response details (content type, length, ETag, metadata) as JSON after saving the body, so adding --query ContentType is a quick way to see how a file was stored without opening it.
Large files: stream, don't buffer
Reading a whole object into a string or byte array is fine for kilobytes and small megabytes. For larger files it can exhaust your memory, especially in Lambda, where memory is what you set for the function. The safe patterns:
- Stream straight to disk:
pipeline(res.Body, createWriteStream(path))in Node,download_filein Python. In Lambda,/tmpholds up to the ephemeral storage you configure. - Process as it flows: pipe the body through a line reader or a decompressor (
zlib.createGunzip()) and handle each line or chunk, so memory stays flat whatever the file size. - Read only what you need with a byte range (next section), for example the header of a big CSV.
- Use the transfer helpers for very large objects: they download in parallel parts and retry failed parts for you.
- Skip the download when you only need a few rows: query the file in place with Athena or S3 Select-style tools instead of pulling it all into your code.
Reading the object that triggered a Lambda function
The most common place GetObject runs is a Lambda function triggered by an upload: a file lands in a bucket, S3 sends an event, and the function reads the file. The event tells you the bucket and key, with one trap that breaks almost everyone's first version:
import urllib.parse
import boto3
s3 = boto3.client("s3")
def handler(event, context):
for record in event["Records"]:
bucket = record["s3"]["bucket"]["name"]
key = urllib.parse.unquote_plus(record["s3"]["object"]["key"]) # the trap
body = s3.get_object(Bucket=bucket, Key=key)["Body"].read()
print(f"read {len(body)} bytes from s3://{bucket}/{key}")The key in the event is URL-encoded: a file called March invoice.pdf arrives as March+invoice.pdf, and accented letters arrive as percent codes. Pass that straight to GetObject and you get NoSuchKey (or AccessDenied) for a file you can see in the console. unquote_plus in Python, or decodeURIComponent(key.replace(/\+/g, " ")) in JavaScript, turns it back into the real key. Files without spaces or special characters work either way, which is why the bug often appears weeks after launch, with the first customer who names a file "Final copy (2).pdf".
Two more Lambda points. Loop over Records rather than assuming there is exactly one, since the event format allows several. And never write the processed result back to the same bucket and prefix that triggers the function: each write fires the trigger again, and the function calls itself in a loop, running up invocations and costs until you notice. Write output to a different prefix that the trigger does not watch, or to a separate bucket.
Jake: "So it worked for every file except the one with a space in the name?"
Ethan: "The space arrives as a plus sign. One decode call, and 'March invoice.pdf' is found again."
Will you read the latest version? Consistency and caching
Since December 2020, S3 gives strong read-after-write consistency for every request in every Region: once an upload or overwrite succeeds, the next GetObject returns the new content, and a successful delete is immediately reflected too. Older advice about waiting or retrying after a write to "let S3 catch up" no longer applies to S3 itself.
Stale content still happens, but the cause is a cache in front of S3:
- CloudFront keeps serving its cached copy until it expires or you invalidate it. Versioned file names (
app.3f2a.js) avoid the problem entirely. - Browsers follow the object's
Cache-Controlheader; a longmax-ageon a file you overwrite means visitors keep the old one. - Your own code may cache the parsed result in memory, for example in a Lambda global variable that survives between invocations.
For files you poll for changes, the conditional read in the next section is the efficient pattern: send the last ETag with IfNoneMatch, and S3 returns the body only when the content has actually changed.
Byte ranges and conditional reads
// First 1 KB only
const head = await s3.send(new GetObjectCommand({ Bucket, Key, Range: "bytes=0-1023" }));
// Only if it changed since you last read it (saves bandwidth)
const fresh = await s3.send(new GetObjectCommand({ Bucket, Key, IfNoneMatch: lastEtag }));
// Unchanged objects return a 304 Not Modified error you can catchRanges are how download managers and video players read big files in pieces, and how you peek at a file's start cheaply. The response to a ranged request has status 206 and a ContentRange header telling you which bytes you got and the full size, so you can work out the next range yourself.
Jake: "So I could read just the CSV header to check the columns?"
Ethan: "First kilobyte, split on the first newline. No need to download the other two gigabytes."
Each ranged GET is billed as one request. To check whether an object exists, or to read its size and metadata without the body at all, use HeadObjectCommand (head_object in boto3).
Reading an object's details without its content
Often you need facts about a file rather than the file: its size before deciding how to read it, its type, when it changed, or a custom value your uploader attached. HeadObject returns all of that without transferring a single byte of content:
head = s3.head_object(Bucket="shop-data", Key="exports/stock.csv")
print(head["ContentLength"], head["ContentType"], head["LastModified"], head["ETag"])
print(head["Metadata"]) # custom x-amz-meta-* values, as a dict
print(head.get("StorageClass", "STANDARD"))
tags = s3.get_object_tagging(Bucket="shop-data", Key="exports/stock.csv")["TagSet"]Three details surprise people. Custom metadata keys come back in lowercase, whatever case you used when uploading, so Metadata={"Issue": "42"} is read back as {"issue": "42"}. StorageClass is left out entirely for objects in S3 Standard, which is why the code above supplies a default. And tags are not part of the object's details at all: they need their own call, get_object_tagging, and their own permission, s3:GetObjectTagging.
A good pattern for large files is "head first, then decide": check ContentLength, read small objects in one go with read() or transformToString(), and stream or download anything over a threshold you choose, such as 50 MB. It costs one cheap extra request and keeps a surprise 3 GB file from taking down a function sized for kilobytes.
GetObject on a "folder": why it fails, and what to do instead
A frequent question is how to GetObject a whole directory. You cannot, because in a normal S3 bucket there is no directory to get. Keys like invoices/2026/a.pdf merely contain slashes, and the console draws folders from them. Asking GetObject for invoices/2026/ returns one of two things:
- A zero-byte object, if someone created the "folder" in the console, which stores an empty marker object with that key. Your code downloads nothing useful and may think it succeeded.
NoSuchKey(or AccessDenied withouts3:ListBucket), if no marker exists, which is the case when files were uploaded with the prefix in their keys.
The correct pattern is two steps: list the keys under the prefix with ListObjectsV2 (paginating past the first 1,000), then GetObject each one, skipping keys that end in a slash. Every SDK has a paginator for the listing part; our S3 listing guide shows it in each language. From a terminal, aws s3 cp s3://shop-data/invoices/2026/ ./invoices --recursive does both steps for you.
Directory buckets, used by the S3 Express One Zone storage class, do have real directories, but the rule is the same: you list the directory and fetch the objects in it. There is still no single call that returns a folder's contents as one download.
Reading many objects quickly
Reading one object is fast; reading ten thousand one after another is slow, because each request waits for the previous one. S3 itself is rarely the limit: it supports at least 5,500 GET and HEAD requests per second for each prefix in a bucket, and more prefixes multiply that. The limit is usually your code doing one thing at a time.
- Read in parallel. In Python, a
ThreadPoolExecutorwith 10 to 50 workers callingget_objecton a shared client speeds up batches of small files enormously. In JavaScript, run severalsend()calls withPromise.allover chunks of keys rather than awaiting each one in turn. - Size the connection pool to match. boto3 keeps 10 connections per client by default; with 50 threads, raise it with
Config(max_pool_connections=50), or the extra threads simply queue for a connection. The JavaScript SDK's warning that socket usage is at capacity means the same thing, or that bodies are not being read. - Batch small records into bigger files. A million 1 KB objects cost a million requests to read; the same data as a hundred files of 10 MB reads far faster and cheaper.
- Run close to the data. Code in the same Region as the bucket gets lower latency per request and pays nothing for transfer.
For reading one huge object fast, the transfer helpers (download_file, S3TransferManager, TransferUtility) already do the parallel part for you, by fetching byte ranges at the same time and joining them.
Garbled text: encodings and the Excel BOM
When text from S3 shows odd characters such as Γ© instead of Γ©, or a strange Γ―»¿ before the first column name, the bytes are fine and the decoding is wrong. Three cases cover nearly all of it:
- A byte-order mark from Excel. CSV files saved by Excel as "CSV UTF-8" start with three invisible bytes. Decode with
"utf-8-sig"in Python (body.decode("utf-8-sig")), which removes them, or your first column's name will not match in code. - Windows-1252 files. Older Windows programs save text in a legacy encoding. Decode with
"cp1252"in Python, ortransformToString("latin1")in JavaScript as a close match. - Compressed files without a hint. If the body starts with the bytes
1f 8b, it is gzip data; decompress it before decoding, whatever the file name says.
The fix belongs at the writing end as well: store text as UTF-8 and set ContentType with charset=utf-8 when uploading, so every reader, including browsers, decodes it the same way.
In the browser, and presigned URLs
In a browser, res.Body is a web ReadableStream, not a Node stream, so Node-only calls such as .pipe() fail with "body.pipe is not a function". The transformToString() and transformToByteArray() helpers work the same, and transformToWebStream() gives you the web stream directly.
For most web apps, though, the browser should not hold AWS credentials at all. Generate a presigned URL on your server and let the browser fetch the file directly:
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
const url = await getSignedUrl(s3, new GetObjectCommand({ Bucket, Key }), { expiresIn: 900 });
// send url to the browser; it can GET the file for 15 minutesIn the browser, the presigned URL is used like any other link: put it in an <a href> or <img src>, or read it in code with const text = await (await fetch(url)).text(). To make the browser save the file under a friendly name rather than display it, sign the URL with ResponseContentDisposition: 'attachment; filename="invoice.pdf"' in the command; S3 then sends that header with the download, without changing the stored object.
When the browser reads the file with fetch from another site's page, the bucket needs a CORS rule; our S3 CORS guide covers it, and our presigned URL guide explains expiry errors.
Handling a missing file gracefully
"Read it if it exists, otherwise use a default" is a common need, and each SDK reports a missing key slightly differently. Worse, GetObject and HeadObject report it differently from each other:
# Python
from botocore.exceptions import ClientError
try:
text = s3.get_object(Bucket="shop-data", Key="settings.json")["Body"].read().decode("utf-8")
except s3.exceptions.NoSuchKey:
text = "{}" # GetObject: a modeled NoSuchKey error
try:
s3.head_object(Bucket="shop-data", Key="settings.json")
exists = True
except ClientError as e:
if e.response["Error"]["Code"] == "404": # HeadObject: just "404", no body to name it
exists = False
else:
raise
// JavaScript v3
try {
const res = await s3.send(new GetObjectCommand({ Bucket, Key }));
} catch (err) {
if (err.name === "NoSuchKey") { /* default */ } // GetObject
}
// HeadObjectCommand throws err.name === "NotFound" insteadThe difference exists because a HEAD response has no body, so S3 cannot include an error code like NoSuchKey; the SDK only sees the 404 status. Code that checks for NoSuchKey after a HeadObject never matches, and treats every missing file as an unexpected failure.
Two habits keep this clean. Catch only the "missing" case and let everything else, especially AccessDenied, raise, so a permission problem is not silently treated as "file not there." And remember the earlier rule: without s3:ListBucket, a missing key returns 403 AccessDenied rather than 404, so the code above sees an access error. If your "file missing" branch never runs, check that permission first.
Reading an older version, or a file someone deleted
In a bucket with versioning turned on, an overwrite keeps the old content as a previous version, and a delete only adds a "delete marker" on top. Both are recoverable with GetObject, which is often the fastest fix for "someone replaced the price list with the wrong one":
- List the versions of the key:
aws s3api list-object-versions --bucket shop-data --prefix prices.json. Each entry has aVersionId, a date and whether it is the latest; delete markers are listed separately. - Read the version you want by passing its
VersionIdto GetObject (--version-idin the CLI). This needss3:GetObjectVersion. - Restore it by copying that version onto the same key, which makes it the current version again, or, for a deleted file, by deleting the delete marker, which brings the previous version back as current.
A plain GetObject on a key whose latest version is a delete marker returns 404, exactly as if the file had never existed, so code that only reads the current version cannot tell "deleted" from "never uploaded." Without versioning, a deleted or overwritten object is gone, which is the strongest argument for turning versioning on in any bucket that holds files people edit.
Permissions GetObject needs
s3:GetObjecton the object ARN (arn:aws:s3:::shop-data/*or a narrower prefix).s3:ListBucketon the bucket ARN, if you want a missing key to return NoSuchKey (404) instead of AccessDenied (403).kms:Decrypton the key, if the object is encrypted with SSE-KMS.s3:GetObjectVersionif you read a specificVersionId.
For a Lambda function or an EC2 instance, these go on the function's execution role or the instance profile, never in access keys inside your code. Keep the resource as narrow as your app allows, for example arn:aws:s3:::shop-data/prices/*, so a bug in your code cannot read the rest of the bucket. Every AccessDenied variant on GetObject, including bucket policies, KMS and VPC endpoints, is in our GetObject AccessDenied guide.
The s3:GetObject family. IAM has several actions with similar names, and policies often need more than one. What each one actually allows:
| Action | Allows | Needed when |
|---|---|---|
s3:GetObject | Reading the current version's content, and HeadObject | Always, for any read or existence check |
s3:GetObjectVersion | Reading a specific older version | Your code passes a VersionId |
s3:GetObjectTagging | Reading an object's tags | Code or copy jobs that carry tags along |
s3:GetObjectAcl | Reading the object's ACL | Rarely now; most buckets have ACLs disabled |
s3:GetObjectVersionForReplication | Reading objects for replication | Only in the replication role's policy |
s3:ListBucket | Listing keys (on the bucket ARN, not /*) | Listing folders, and getting 404 instead of 403 for missing keys |
Note that there is no separate HeadObject permission: s3:GetObject covers it. And s3:PutObject, which people often add "just in case," allows writing and overwriting, so leave it out of read-only roles.
What GetObject costs
Reading from S3 costs two things: requests and data transfer.
- Requests: GET requests in S3 Standard cost about $0.0004 per 1,000 in US Regions, ten times cheaper than uploads. Each ranged GET counts as one request, so reading a file in 1,000 small ranges costs 1,000 requests.
- Transfer to the internet: about $0.09 per GB in US Regions after the first 100 GB a month, which AWS gives free across your account. This is the line that grows when a popular file is downloaded straight from S3; serving it through CloudFront usually costs less and is faster.
- Transfer inside AWS: free to EC2, Lambda and other services in the same Region. Reading from a bucket in another Region adds a cross-Region transfer charge per GB.
- Retrieval fees: infrequent-access and archive classes, such as Standard-IA and Glacier Instant Retrieval, charge per GB read on top of the request, which is why they suit data you seldom open.
For Jake's price list, read a few thousand times a day by a Lambda function in the same Region, the monthly cost of all those GetObject calls is well under a dollar. The cost that catches people is the big file linked publicly, downloaded thousands of times from the internet.
GetObject errors, fixed
| What you see | Cause | Fix |
|---|---|---|
[object Object] instead of the file's text | SDK v3 Body is a stream; toString() describes the stream | await res.Body.transformToString() |
.promise is not a function | v2 code running against v3 | Use s3.send(new GetObjectCommand(...)) |
| Body empty the second time you read it | Streams can be read only once | Store the first result in a variable |
body.pipe is not a function | Browser web stream, not a Node stream | Use the transformTo... helpers |
| Warnings that socket usage is at capacity; requests slow or time out | Bodies left unread keep connections open | Always read or destroy each Body |
NoSuchKey (404) | Wrong key, case, prefix or Region | Check the exact key; see our NoSuchKey guide |
AccessDenied (403) | Missing s3:GetObject, KMS, or a bucket policy deny (or a missing key without ListBucket) | Fix the policy; add ListBucket to see 404s |
| Lambda runs out of memory on a big file | Whole object loaded into a string or buffer | Stream to /tmp or process chunks |
| Garbled characters | File is not UTF-8 | Pass the right encoding to transformToString or decode() |
| Gzip bytes instead of text | Object stored compressed | Decompress with zlib / gzip after reading |
Missing-key problems have their own checklist in our NoSuchKey guide, and "could not load credentials" before the call even starts is covered in our SDK credentials guide.
Frequently asked questions
How do I read an S3 object as a string in AWS SDK v3?
Send GetObjectCommand, then call await res.Body.transformToString().
Why does Body.toString() return [object Object] in SDK v3?
In v3 the Body is a stream, not a Buffer. Use transformToString() or transformToByteArray().
How do I read a JSON file from S3 in JavaScript?
JSON.parse(await res.Body.transformToString()).
How do I save an S3 object to a file in Node.js?
await pipeline(res.Body, createWriteStream(path)) with pipeline from node:stream/promises.
How do I read an S3 object in Python boto3?
s3.get_object(Bucket=..., Key=...)["Body"].read().decode("utf-8"), or s3.download_file() for files.
How do I read a large S3 file line by line in Python?
Iterate over obj["Body"].iter_lines(), decoding each line.
How do I print an S3 object with the AWS CLI?
aws s3 cp s3://bucket/key - writes it to standard output.
What is the difference between Get-S3Object and Read-S3Object?
Get-S3Object lists objects; Read-S3Object downloads an object's content to a file.
Can I read the S3 Body twice?
No. A stream can be read once; keep the result in a variable.
How do I read only part of an S3 object?
Pass Range: "bytes=0-1023" to GetObject, or --range in the CLI.
How do I check if an S3 object exists without downloading it?
Use HeadObject: it returns size and metadata, or a 404 if the key does not exist.
What permissions does GetObject need?
s3:GetObject on the object, kms:Decrypt for SSE-KMS objects, and s3:ListBucket if you want 404s for missing keys.
How do I let a browser download a private S3 file?
Create a presigned URL on your server with getSignedUrl and give it to the browser.
What is the TypeScript type of the S3 Body?
A union for Node and browsers; use transformToString without a cast, or cast to Readable for Node stream APIs.
Why do my S3 requests slow down after many GetObject calls?
Unread bodies keep sockets open; read or destroy every Body so connections return to the pool.
How do I migrate getObject from SDK v2 to v3?
Replace s3.getObject(params).promise() with s3.send(new GetObjectCommand(params)) and Body.toString() with await Body.transformToString().
How do I download a whole S3 object in Java?
With SDK for Java v2, s3.getObjectAsBytes(request).asUtf8String() for text, or s3.getObject(request, Paths.get(path)) to save it to a file.
What replaced getObjectContent() in Java SDK v2?
getObject now returns a ResponseInputStream directly, and its response() method gives the metadata that getObjectMetadata() used to.
Is the AWS SDK for Java 1.x still supported?
No. It reached end-of-support on December 31, 2025. Existing code keeps working, but new code should use 2.x.
How do I read an S3 object in Go?
Call client.GetObject with a GetObjectInput, defer out.Body.Close(), then io.ReadAll or io.Copy the Body.
How do I read an S3 object in C#?
await client.GetObjectAsync(bucket, key), then read response.ResponseStream with a StreamReader inside using blocks.
Can I GetObject a folder in S3?
No. List the keys under the prefix with ListObjectsV2, then GetObject each one, or use aws s3 cp with --recursive.
Does HeadObject need its own permission?
No. HeadObject is covered by s3:GetObject; add s3:ListBucket on the bucket to get 404 instead of 403 for missing keys.
How much does S3 GetObject cost?
About $0.0004 per 1,000 GET requests in S3 Standard in US Regions, plus internet transfer of about $0.09 per GB after 100 GB free a month.
Why does HeadObject return NotFound instead of NoSuchKey?
A HEAD response has no body, so S3 cannot name the error. boto3 shows code "404" and the JavaScript SDK shows NotFound.
Why does my Lambda get NoSuchKey for a file that exists?
The key in the S3 event is URL-encoded. Decode it with urllib.parse.unquote_plus, or decodeURIComponent after replacing + with a space.
Why are my S3 metadata keys lowercase?
S3 stores custom x-amz-meta-* keys in lowercase, so "Issue" comes back as "issue". Read them with lowercase names.
How do I read many S3 files faster in Python?
Fetch them in parallel with a ThreadPoolExecutor and one shared client, and raise max_pool_connections to match the number of threads.
How do I read a deleted S3 file?
Only if versioning was on: list the versions, read the one you need with VersionId, or delete the delete marker to restore it.
How do I read a gzip file from S3 in Python?
Wrap the body: gzip.GzipFile(fileobj=obj["Body"]) and iterate over it; it decompresses as it streams.
For readers preparing for an AWS certification
We have been covering AWS certifications alongside our fixes, so here is a short extra for readers studying for one. If you only came for the fix, you already have it; feel free to skip this part.
Exams that test this topic: Developer – Associate (DVA-C03 from December 1, 2026) • Solutions Architect – Associate (SAA-C03) • CloudOps Engineer – Associate (SOA-C03).
Here are the exam-style questions this topic tends to raise, with the reasoning you need to answer them:
1. A web app must let browsers download private S3 objects without AWS credentials. What should the server provide?
A presigned URL for GetObject with a short expiry.
2. Which S3 API checks whether an object exists and returns its metadata without the content?
HeadObject.
3. Which IAM permission lets a Lambda function read objects from a bucket?
s3:GetObject on the object ARN (plus kms:Decrypt for SSE-KMS objects).
4. A function must read only the first kilobyte of a large S3 object. How?
A GetObject request with a Range header such as bytes=0-1023.
5. Why should a missing key return 404 instead of 403 for your application, and what enables it?
So code can tell "not found" from "denied"; grant s3:ListBucket on the bucket.
6. How should an application on EC2 get credentials to read S3?
From an IAM role attached to the instance, not from access keys in code.
7. A Lambda function runs out of memory reading a 2 GB S3 object. What is the better approach?
Stream the object to /tmp or process it in chunks instead of loading it into memory.
Exam codes and dates change often. Our AWS certification changes page keeps track of what is current.
Jake's Lambda now returns the price list in 40 milliseconds: GetObjectCommand, transformToString, JSON.parse, done. When the shop later added a 2 GB nightly export, he did not reuse that code; he streamed it to /tmp with pipeline, and the function's memory graph stayed flat. Ethan's one-line review comment on the pull request: "Tap, not glass. Good."
📌 If you keep one line from this page
GetObject's Body is a stream: in SDK v3 read it with transformToString or pipe it to a file, in boto3 call read() or download_file, read it only once, and never leave a body unread.
toString() = [object Object] · Range for partial reads · HeadObject to check existence · presigned URLs for browsers.
Revision note. Written October 19, 2026. An S3 Body is a tap you open once; every error on this page comes from treating it as a glass.