tar 패키지는 Dart에서 tar 파일 형식을 읽고 쓰기 위한 메모리 효율적이고 스트리밍 방식의 구현을 제공합니다. 전체 파일을 메모리에 로드하지 않고도 큰 아카이브를 처리할 수 있도록 설계되었으며, 아카이브 항목의 증분 처리를 지원합니다. 특히 제한된 리소스 환경에서 효율적인 파일 압축 및 추출이 필요한 애플리케이션에 적합합니다. 이 패키지는 모바일, 웹, 데스크톱을 포함한 모든 주요 플랫폼과 호환됩니다. Flutter 앱과의 원활한 통합을 가능하게 하며, 강력한 아카이브 처리 기능이 필요한 애플리케이션에 적합합니다.
사용 사례
큰 tar 파일의 스트리밍 추출
자원 제한 환경에서의 효율적인 아카이브 생성
크로스 플랫폼 앱에서 tar 기반 데이터 저장 통합
아카이브된 로그 또는 백업 처리
Flutter 애플리케이션에서 압축된 자산 처리
주요 기능
낮은 메모리 사용을 위한 스트리밍 I/O
tar 아카이브 읽기 및 쓰기 지원
크로스 플랫폼 호환성 (Android, iOS, Web, macOS, Windows, Linux)
아카이브 항목의 증분 처리
경량이고 빠른 성능
적합한 대상
파일 관리 도구를 개발하는 개발자
효율적인 아카이브 처리가 필요한 앱
메모리 자원이 제한된 프로젝트
Flutter를 사용한 크로스 플랫폼 애플리케이션
압축 형식의 대규모 데이터 세트를 처리하는 도구
고려 사항
암호화되거나 압축된 tar 파일 (.tar.gz 등)을 지원하지 않습니다
파일 권한 및 메타데이터를 수동으로 처리해야 합니다
고급 기능 없이 기본 tar 형식에만 제한됨
복잡한 아카이브 작업에 적합하지 않습니다
알려진 잘 형성된 tar 입력과 함께 사용하는 것이 가장 좋습니다
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
tar
This package provides stream-based readers and writers for tar files.
When working with large tar files, this library consumes considerably less memory
than package:archive, although it is slightly slower due to the async overhead.
Reading
To read entries from a tar file, use a TarReader with a Stream emitting bytes (as List<int>):
import'dart:convert';
import'dart:io';
import'package:tar/tar.dart';
Future<void> main() async {
final reader = TarReader(File('file.tar').openRead());
while (await reader.moveNext()) {
final entry = reader.current;
// Use reader.header to see the header of the current tar entryprint(entry.header.name);
// And reader.contents to read the content of the current entry as a streamprint(await entry.contents.transform(utf8.decoder).first);
}
// Note that the reader will automatically close if moveNext() returns false or// throws. If you want to close a tar stream before that happens, use// reader.cancel();
}
To read .tar.gz files, transform the stream with gzip.decoder before
passing it to the TarReader.
To easily go through all entries in a tar file, use TarReader.forEach:
Warning: Since the reader is backed by a single stream, concurrent calls to
read are not allowed! Similarly, if you're reading from an entry's contents,
make sure to fully drain the stream before calling read() again.
Not subscribing to contents before calling moveNext() is acceptable too.
In this case, the reader will implicitly drain the stream.
The reader detects concurrency misuses and will throw an error when they occur,
there's no risk of reading faulty data.
Writing
When writing archives, package:tar expects a Stream of tar entries to include in
the archive.
This stream can then be converted into a stream of byte-array chunks forming the
encoded tar archive.
To write a tar stream into a StreamSink<List<int>>, such as an IOSink returned by
File.openWrite, use tarWritingSink:
By default, tar files are written in the pax format defined by the
POSIX.1-2001 specification (--format=posix in GNU tar).
When all entries have file names shorter than 100 chars and a size smaller
than 8 GB, this is equivalent to the ustar format. This library won't write
PAX headers when there is no reason to do so.
If you prefer writing GNU-style long filenames instead, you can use the
format option:
To change the output format on the tarWriter transformer, use
tarWriterWith.
Synchronous writing
As the content of tar entries is defined as an asynchronous stream, the tar encoder is asynchronous too.
The more specific SynchronousTarEntry class stores tar content as a list of bytes, meaning that it can be
written synchronously.
To synchronously write tar files, use tarConverter (or tarConverterWith for options):
List<int> createTarArchive(Iterable<SynchronousTarEntry> entries) {
lateList<int> result;
final sink = ByteConversionSink.withCallback((data) => result = data);
final output = tarConverter.startChunkedConversion(sink);
entries.forEach(output.add);
output.close();
return result;
}
Features
Supports v7, ustar, pax, gnu and star archives
Supports extended pax headers for long file or link names
Supports long file and link names generated by GNU-tar
Hardened against denial-of-service attacks with invalid tar files
Supports being compiled to JavaScript, tested on Node.js
Security considerations
Internally, this package contains checks to guard against some invalid tar files.
In particular,
The reader doesn't allocate memory based on values in a tar file (so there's
a guard against DoS attacks with tar files containing huge headers).
When encountering malformed tar files, the reader will throw a TarException.
Any other exception thrown indicates a bug in package:tar or how it's used.
The reader should never crash.
Reading a tar file can be cancelled mid-stream without leaking resources.
However, the tar reader does not throw exceptions for well-formed archives
with suspicious contents, such as
File names beginning with ../, / or names pointing out of the archive by
other means.
Link references to files outside of the archive.
Paths not using forward slashes.
Gzip + tar bombs.
Invalid permission bits in entries.
...
When reading or extracting untrusted tar files, it is your responsibility to
detect and handle these cases.
For instance, this naive extraction function is susceptible to invalid tar
files containing paths outside of the target directory:
Future<void> extractTarGz(File tarGz, Directory target) async {
final input = tarGz.openRead().transform(gzip.decoder);
awaitTarReader.forEach(input, (entry) async {
final destination =
// DON'T DO THIS! If `entry.name` contained `../`, this may escape the// target directory.
path.joinAll([target.path, ...path.posix.split(entry.name)]);
final f = File(destination);
await f.create(recursive: true);
await entry.contents.pipe(f.openWrite());
});
}
For an idea on how to guard against this, see the extraction logic
used by the pub client.
Big thanks to Garett Tok Ern Liang for writing the initial
Dart tar reader that this library is based on.