CodeSampleX

Пример

fs-extra 9.1.0: readJson

Проверенный пример — npm fs-extra 9.1.0: readJson. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: fs-extra.readJson asynchronously reads…

sha256:07ec6ea5e84d5f203494b97703990de1c3a5a3df6457e0691e3b5b07e3dbd5be

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Среды запусков проверки

Окружение Контракт Этапы Запуск
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-23

Кейс

HOW
Цель
verify fs-extra.readJson in pkg:npm/fs-extra@9.1.0
Пакеты
Символы
  • fs-extra.readJson
Окружение
node 22.23.2
Создан
2026-08-23T05:24:30Z

Контракт

  1. fs-extra.readJson asynchronously reads a JSON file and parses it into an object
  2. fs-extra.readJsonSync synchronously reads a JSON file and parses it into an object
  3. fs-extra.readJson with throws: false returns null on invalid JSON instead of throwing an error
  4. fs-extra.readJson rejects with ENOENT when the specified file does not exist

Файлы

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

Скачать артефакт с исходным кодом (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: verify fs-extra.readJson in pkg:npm/fs-extra@9.1.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/fs-extra@9.1.0
Demonstrate these symbols/APIs:
  - fs-extra.readJson
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:32f0e6c34df9d0f1b7a2e6cd68f4c7c2d3cea25a560269fc436422fc5e6b019f","constraints":{"executionContext":"node"},"contract":["fs-extra.readJson asynchronously reads a JSON file and parses it into an object","fs-extra.readJsonSync synchronously reads a JSON file and parses it into an object","fs-extra.readJson with throws: false returns null on invalid JSON instead of throwing an error","fs-extra.readJson rejects with ENOENT when the specified file does not exist"],"goal":"verify fs-extra.readJson in pkg:npm/fs-extra@9.1.0","kind":"HOW","packages":["pkg:npm/fs-extra@9.1.0"],"schemaVersion":1,"symbols":["fs-extra.readJson"]},"contractCommand":["node","test/contract.cjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/fs-extra@9.1.0"],"schemaVersion":1,"subject":"pkg:npm/fs-extra@9.1.0","symbols":["fs-extra.readJson"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

const fse = require('fs-extra');

async function readJsonFile(filePath, options = {}) {
  return await fse.readJson(filePath, options);
}

function readJsonFileSync(filePath, options = {}) {
  return fse.readJsonSync(filePath, options);
}

module.exports = {
  readJsonFile,
  readJsonFileSync,
  fse
};
package-lock.json
{
  "name": "sample-fs-extra-readjson",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-fs-extra-readjson",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "fs-extra": "9.1.0"
      }
    },
    "node_modules/at-least-node": {
      "version": "1.0.0",
      "resolved": "https://registry.npmjs.org/at-least-node/-/at-least-node-1.0.0.tgz",
      "integrity": "sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==",
      "license": "ISC",
      "engines": {
        "node": ">= 4.0.0"
      }
    },
    "node_modules/fs-extra": {
      "version": "9.1.0",
      "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz",
      "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==",
      "license": "MIT",
      "dependencies": {
        "at-least-node": "^1.0.0",
        "graceful-fs": "^4.2.0",
        "jsonfile": "^6.0.1",
        "universalify": "^2.0.0"
      },
      "engines": {
        "node": ">=10"
      }
    },
    "node_modules/graceful-fs": {
      "version": "4.2.11",
      "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
      "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
      "license": "ISC"
    },
    "node_modules/jsonfile": {
      "version": "6.2.1",
      "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
      "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
      "license": "MIT",
      "dependencies": {
        "universalify": "^2.0.0"
      },
      "optionalDependencies": {
        "graceful-fs": "^4.1.6"
      }
    },
    "node_modules/universalify": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
      "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
      "license": "MIT",
      "engines": {
        "node": ">= 10.0.0"
      }
    }
  }
}
package.json
{
  "name": "sample-fs-extra-readjson",
  "version": "1.0.0",
  "private": true,
  "description": "verify fs-extra.readJson in pkg:npm/fs-extra@9.1.0",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.cjs"
  },
  "dependencies": {
    "fs-extra": "9.1.0"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify fs-extra.readJson in pkg:npm/fs-extra@9.1.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/fs-extra@9.1.0"
  ],
  "symbols": [
    "fs-extra.readJson"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.cjs
'use strict';

const assert = require('assert');
const fs = require('fs');
const path = require('path');
const os = require('os');
const fse = require('fs-extra');
const { readJsonFile, readJsonFileSync } = require('../index.js');

async function run() {
  const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'fse-readjson-test-'));
  const validJsonFile = path.join(tmpDir, 'valid.json');
  const invalidJsonFile = path.join(tmpDir, 'invalid.json');
  const missingFile = path.join(tmpDir, 'non-existent.json');

  const sampleData = {
    name: 'test-package',
    version: '1.0.0',
    features: ['readJson', 'readJsonSync'],
    meta: {
      active: true,
      count: 42
    }
  };

  try {
    fs.writeFileSync(validJsonFile, JSON.stringify(sampleData, null, 2), 'utf8');
    fs.writeFileSync(invalidJsonFile, '{ invalid json content: 123', 'utf8');

    // 1. Asynchronous fse.readJson reads and parses valid JSON
    const asyncResult = await fse.readJson(validJsonFile);
    assert.deepStrictEqual(asyncResult, sampleData, 'fse.readJson should correctly parse valid JSON');

    // 2. Synchronous fse.readJsonSync reads and parses valid JSON
    const syncResult = fse.readJsonSync(validJsonFile);
    assert.deepStrictEqual(syncResult, sampleData, 'fse.readJsonSync should correctly parse valid JSON');

    // 3. Helper functions from index.js
    const helperAsyncResult = await readJsonFile(validJsonFile);
    assert.deepStrictEqual(helperAsyncResult, sampleData, 'readJsonFile helper should parse JSON correctly');

    const helperSyncResult = readJsonFileSync(validJsonFile);
    assert.deepStrictEqual(helperSyncResult, sampleData, 'readJsonFileSync helper should parse JSON correctly');

    // 4. Options: throws: false returns null for malformed JSON instead of throwing
    const asyncInvalidWithNoThrow = await fse.readJson(invalidJsonFile, { throws: false });
    assert.strictEqual(asyncInvalidWithNoThrow, null, 'fse.readJson with throws: false should return null for malformed JSON');

    const syncInvalidWithNoThrow = fse.readJsonSync(invalidJsonFile, { throws: false });
    assert.strictEqual(syncInvalidWithNoThrow, null, 'fse.readJsonSync with throws: false should return null for malformed JSON');

    // 5. Malformed JSON with throws: true (default) rejects / throws SyntaxError
    await assert.rejects(
      async () => {
        await fse.readJson(invalidJsonFile);
      },
      (err) => err instanceof SyntaxError || (err && err.name === 'SyntaxError'),
      'fse.readJson should throw SyntaxError for invalid JSON by default'
    );

    assert.throws(
      () => {
        fse.readJsonSync(invalidJsonFile);
      },
      (err) => err instanceof SyntaxError || (err && err.name === 'SyntaxError'),
      'fse.readJsonSync should throw SyntaxError for invalid JSON by default'
    );

    // 6. Non-existent file rejects / throws error with code ENOENT
    await assert.rejects(
      async () => {
        await fse.readJson(missingFile);
      },
      (err) => err && err.code === 'ENOENT',
      'fse.readJson should reject with ENOENT for non-existent file'
    );

    assert.throws(
      () => {
        fse.readJsonSync(missingFile);
      },
      (err) => err && err.code === 'ENOENT',
      'fse.readJsonSync should throw with ENOENT for non-existent file'
    );

    console.log('Contract tests passed successfully.');
    process.exit(0);
  } finally {
    try {
      if (fs.existsSync(tmpDir)) {
        fs.rmSync(tmpDir, { recursive: true, force: true });
      }
    } catch (e) {
      // Ignore cleanup error
    }
  }
}

run().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

Исходный сидер

аноним