CodeSampleX

Пример

fs-extra 8.1.0: readJson

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

sha256:41cffaacdbda82fe4c12194203178a6ecbe897ff36635d96afccc53d98f066a0

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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@8.1.0
Пакеты
Символы
  • fs-extra.readJson
Окружение
node 22.23.2
Создан
2026-08-23T04:44:14Z

Контракт

  1. fs-extra.readJson asynchronously reads a JSON file and parses it into a JavaScript object
  2. fs-extra.readJson returns a promise when no callback is provided and supports node-style callback
  3. fs-extra.readJsonSync synchronously reads and parses a JSON file into a JavaScript object
  4. fs-extra.readJson supports custom reviver option to transform parsed values
  5. fs-extra.readJson and readJsonSync return null when throws option is set to false on invalid JSON

Файлы

  • 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@8.1.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/fs-extra@8.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:772a86a4ae75ba5283bc60097d258004748648bc7cc4ddebe40b60f5fa8b036d","constraints":{"executionContext":"node"},"contract":["fs-extra.readJson asynchronously reads a JSON file and parses it into a JavaScript object","fs-extra.readJson returns a promise when no callback is provided and supports node-style callback","fs-extra.readJsonSync synchronously reads and parses a JSON file into a JavaScript object","fs-extra.readJson supports custom reviver option to transform parsed values","fs-extra.readJson and readJsonSync return null when throws option is set to false on invalid JSON"],"goal":"verify fs-extra.readJson in pkg:npm/fs-extra@8.1.0","kind":"HOW","packages":["pkg:npm/fs-extra@8.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@8.1.0"],"schemaVersion":1,"subject":"pkg:npm/fs-extra@8.1.0","symbols":["fs-extra.readJson"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

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

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

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

function readJsonFileCallback(filePath, options, callback) {
  if (typeof options === 'function') {
    callback = options;
    options = {};
  }
  return fs.readJson(filePath, options, callback);
}

module.exports = {
  readJsonFile,
  readJsonFileSync,
  readJsonFileCallback,
  fs
};
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": "8.1.0"
      }
    },
    "node_modules/fs-extra": {
      "version": "8.1.0",
      "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz",
      "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==",
      "license": "MIT",
      "dependencies": {
        "graceful-fs": "^4.2.0",
        "jsonfile": "^4.0.0",
        "universalify": "^0.1.0"
      },
      "engines": {
        "node": ">=6 <7 || >=8"
      }
    },
    "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": "4.0.0",
      "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz",
      "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==",
      "license": "MIT",
      "optionalDependencies": {
        "graceful-fs": "^4.1.6"
      }
    },
    "node_modules/universalify": {
      "version": "0.1.2",
      "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",
      "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==",
      "license": "MIT",
      "engines": {
        "node": ">= 4.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@8.1.0",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.cjs"
  },
  "dependencies": {
    "fs-extra": "8.1.0"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify fs-extra.readJson in pkg:npm/fs-extra@8.1.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/fs-extra@8.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, readJsonFileCallback } = require('../index.js');

async function run() {
  const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'fse-readjson-contract-'));

  try {
    // 1. Asynchronously read and parse JSON file with Promise
    const validJsonFile = path.join(tmpDir, 'valid.json');
    const validData = {
      name: 'sample-readjson',
      version: '8.1.0',
      count: 42,
      active: true,
      features: ['promise', 'callback', 'sync']
    };
    fs.writeFileSync(validJsonFile, JSON.stringify(validData, null, 2), 'utf8');

    const readAsync = await fse.readJson(validJsonFile);
    assert.deepStrictEqual(readAsync, validData, 'readJson content should match original data');

    // 2. Asynchronously read JSON file using callback
    const readCallback = await new Promise((resolve, reject) => {
      fse.readJson(validJsonFile, (err, data) => {
        if (err) return reject(err);
        resolve(data);
      });
    });
    assert.deepStrictEqual(readCallback, validData, 'readJson callback content should match original data');

    // 3. Synchronously read and parse JSON file
    const readSync = fse.readJsonSync(validJsonFile);
    assert.deepStrictEqual(readSync, validData, 'readJsonSync content should match original data');

    // 4. Reviver option support
    const reviver = (key, value) => {
      if (typeof value === 'number') {
        return value * 2;
      }
      return value;
    };
    const readRevived = await fse.readJson(validJsonFile, { reviver });
    assert.strictEqual(readRevived.count, 84, 'reviver should have doubled count');
    assert.strictEqual(readRevived.name, 'sample-readjson', 'reviver should keep string property');

    // 5. Throws option (throws: false returns null on invalid JSON)
    const invalidJsonFile = path.join(tmpDir, 'invalid.json');
    fs.writeFileSync(invalidJsonFile, '{ invalid json string }', 'utf8');

    const readInvalidThrowsFalse = await fse.readJson(invalidJsonFile, { throws: false });
    assert.strictEqual(readInvalidThrowsFalse, null, 'readJson with throws: false should return null');

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

    // 6. Test helper functions
    const helperReadData = await readJsonFile(validJsonFile);
    assert.deepStrictEqual(helperReadData, validData, 'Helper readJsonFile should match valid data');

    const helperSyncData = readJsonFileSync(validJsonFile);
    assert.deepStrictEqual(helperSyncData, validData, 'Helper readJsonFileSync should match valid data');

    const helperCallbackData = await new Promise((resolve, reject) => {
      readJsonFileCallback(validJsonFile, (err, data) => {
        if (err) return reject(err);
        resolve(data);
      });
    });
    assert.deepStrictEqual(helperCallbackData, validData, 'Helper readJsonFileCallback should match valid data');

    console.log('Contract tests passed successfully.');
  } finally {
    try {
      fse.removeSync(tmpDir);
    } catch (e) {
      // Ignore cleanup error
    }
  }
}

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

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

аноним