CodeSampleX

샘플

get-stream 6.0.1: read readable stream to string with encoding and maxBuffer options using get-stream

검증된 샘플 — npm get-stream 6.0.1: read readable stream to string with encoding and maxBuffer options using get-stream. node 22 · linux alpine/x64 · docker에서…

sha256:3f3b9c9629f127dcfec0f6e7c79ceab74501b3901af68bec92befc267284bf9c

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 npm

검증 실행 환경

환경 컨트랙트 단계 실행일
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-27

케이스

HOW
목표
read readable stream to string with encoding and maxBuffer options using get-stream
패키지
심벌
  • getStream
생성일
2026-08-27T12:31:55Z

컨트랙트

  1. getStream reads a readable stream and resolves to its complete string content
  2. getStream decodes stream chunks using the specified encoding option
  3. getStream resolves to an empty string when given an empty readable stream
  4. getStream rejects with MaxBufferError when stream content length exceeds maxBuffer option
  5. getStream rejects with the emitted error when the stream encounters an error
  6. getStream rejects with an error when called without a stream argument

파일

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • test/contract.mjs

소스 아티팩트 내려받기 (tar.gz)

소스

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: read readable stream to string with encoding and maxBuffer options using get-stream
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/get-stream@6.0.1
Demonstrate these symbols/APIs:
  - getStream

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:a35daad4a29f81ab9ad9ee7d48976af3e2094124b745dc400415fff4fd36f0a3","contract":["getStream reads a readable stream and resolves to its complete string content","getStream decodes stream chunks using the specified encoding option","getStream resolves to an empty string when given an empty readable stream","getStream rejects with MaxBufferError when stream content length exceeds maxBuffer option","getStream rejects with the emitted error when the stream encounters an error","getStream rejects with an error when called without a stream argument"],"goal":"read readable stream to string with encoding and maxBuffer options using get-stream","kind":"HOW","packages":["pkg:npm/get-stream@6.0.1"],"schemaVersion":1,"symbols":["getStream"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/get-stream@6.0.1"],"schemaVersion":1,"subject":"pkg:npm/get-stream@6.0.1","symbols":["getStream"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-get-stream",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-get-stream",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "get-stream": "6.0.1"
      }
    },
    "node_modules/get-stream": {
      "version": "6.0.1",
      "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz",
      "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==",
      "license": "MIT",
      "engines": {
        "node": ">=10"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    }
  }
}
package.json
{
  "name": "sample-get-stream",
  "version": "1.0.0",
  "private": true,
  "license": "MIT-0",
  "main": "src/index.js",
  "dependencies": {
    "get-stream": "6.0.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "read readable stream to string with encoding and maxBuffer options using get-stream",
  "kind": "HOW",
  "packages": [
    "pkg:npm/get-stream@6.0.1"
  ],
  "symbols": [
    "getStream"
  ]
}
src/index.js
const getStream = require('get-stream');

/**
 * Reads a readable stream and resolves to its string content.
 *
 * @param {import('node:stream').Readable} stream - The stream to read.
 * @param {object} [options] - Optional options passed to get-stream.
 * @returns {Promise<string>} The stream content as a string.
 */
async function readStreamToString(stream, options) {
  return getStream(stream, options);
}

/**
 * Reads a stream using a specific character encoding.
 *
 * @param {import('node:stream').Readable} stream - The stream to read.
 * @param {string} encoding - The character encoding (e.g., 'utf8', 'hex', 'base64').
 * @returns {Promise<string>} The decoded string.
 */
async function readStreamWithEncoding(stream, encoding) {
  return getStream(stream, { encoding });
}

/**
 * Reads a stream with a maximum buffer size limit.
 *
 * @param {import('node:stream').Readable} stream - The stream to read.
 * @param {number} maxBuffer - Maximum allowed character length.
 * @returns {Promise<string>} The stream content as a string.
 */
async function readStreamWithLimit(stream, maxBuffer) {
  return getStream(stream, { maxBuffer });
}

module.exports = {
  getStream,
  readStreamToString,
  readStreamWithEncoding,
  readStreamWithLimit,
  MaxBufferError: getStream.MaxBufferError
};
test/contract.mjs
import assert from 'node:assert/strict';
import { Readable } from 'node:stream';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const getStream = require('get-stream');
const {
  readStreamToString,
  readStreamWithEncoding,
  readStreamWithLimit,
  MaxBufferError
} = require('../src/index.js');

async function testReadStreamToString() {
  const stream = Readable.from(['hello ', 'world', '!']);
  const result = await getStream(stream);
  assert.strictEqual(typeof result, 'string');
  assert.strictEqual(result, 'hello world!');

  const bufStream = Readable.from([Buffer.from('stream '), Buffer.from('data')]);
  const bufResult = await readStreamToString(bufStream);
  assert.strictEqual(bufResult, 'stream data');
}

async function testReadStreamWithEncoding() {
  const data = 'Hello, CodeSampleX!';
  const hexExpected = Buffer.from(data).toString('hex');
  const base64Expected = Buffer.from(data).toString('base64');

  const streamHex = Readable.from([Buffer.from(data)]);
  const hexResult = await getStream(streamHex, { encoding: 'hex' });
  assert.strictEqual(hexResult, hexExpected);

  const streamBase64 = Readable.from([Buffer.from(data)]);
  const base64Result = await readStreamWithEncoding(streamBase64, 'base64');
  assert.strictEqual(base64Result, base64Expected);
}

async function testEmptyStream() {
  const stream = Readable.from([]);
  const result = await getStream(stream);
  assert.strictEqual(typeof result, 'string');
  assert.strictEqual(result, '');

  const helperStream = Readable.from([]);
  const helperResult = await readStreamToString(helperStream);
  assert.strictEqual(helperResult, '');
}

async function testMaxBufferLimit() {
  const stream = Readable.from(['long content exceeding limit']);
  await assert.rejects(
    async () => {
      await getStream(stream, { maxBuffer: 5 });
    },
    (err) => {
      assert.ok(err instanceof MaxBufferError || err.name === 'MaxBufferError', 'should be MaxBufferError');
      assert.strictEqual(err.message, 'maxBuffer exceeded');
      return true;
    }
  );

  const helperStream = Readable.from(['another long content']);
  await assert.rejects(
    async () => {
      await readStreamWithLimit(helperStream, 4);
    },
    (err) => {
      assert.ok(err instanceof MaxBufferError || err.name === 'MaxBufferError', 'should be MaxBufferError');
      assert.strictEqual(err.message, 'maxBuffer exceeded');
      return true;
    }
  );
}

async function testStreamError() {
  const customError = new Error('simulated stream error');
  const stream = new Readable({
    read() {
      this.destroy(customError);
    }
  });

  await assert.rejects(
    async () => {
      await getStream(stream);
    },
    (err) => {
      assert.strictEqual(err, customError);
      return true;
    }
  );
}

async function testMissingStream() {
  await assert.rejects(
    async () => {
      await getStream(null);
    },
    {
      message: 'Expected a stream'
    }
  );

  await assert.rejects(
    async () => {
      await readStreamToString(undefined);
    },
    {
      message: 'Expected a stream'
    }
  );
}

async function runAll() {
  await testReadStreamToString();
  await testReadStreamWithEncoding();
  await testEmptyStream();
  await testMaxBufferLimit();
  await testStreamError();
  await testMissingStream();
  console.log('All getStream contract tests passed successfully.');
}

await runAll();

오리진 시더

익명