CodeSampleX

Пример

write-file-atomic 6.0.0: writeFile, writeFile.sync

Проверенный пример — npm write-file-atomic 6.0.0: writeFile, writeFile.sync. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден.

sha256:44f9d292c084a2f188d3f82feed38bc90ed02499853f1fb443c8c16ade3a5341

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

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

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

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

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

Окружение Контракт Этапы Запуск
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-10-18

Кейс

HOW
Цель
verify pkg:npm/write-file-atomic@6.0.0
Пакеты
Символы
  • writeFile
  • writeFile.sync
Окружение
node
Создан
2026-10-18T10:15:54Z

Контракт

  1. writeFile atomically writes string and Buffer data asynchronously returning a Promise
  2. writeFile supports encoding, mode, fsync, and tmpfileCreated options asynchronously
  3. writeFile serializes concurrent writes to the same file and preserves existing mode on overwrite
  4. writeFile.sync (and sync export) atomically writes string and Uint8Array data synchronously
  5. writeFile supports Node-style callback parameter
  6. Both async and sync reject or throw when target parent directory does not exist and leave no temp files

Файлы

  • 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: verify pkg:npm/write-file-atomic@6.0.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/write-file-atomic@6.0.0

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:8d7ade71561b82b546e84d5b3e4400d9d2276e53cff1a8158fa3acd3bacd29be","contract":["writeFile atomically writes string and Buffer data asynchronously returning a Promise","writeFile supports encoding, mode, fsync, and tmpfileCreated options asynchronously","writeFile serializes concurrent writes to the same file and preserves existing mode on overwrite","writeFile.sync (and sync export) atomically writes string and Uint8Array data synchronously","writeFile supports Node-style callback parameter","Both async and sync reject or throw when target parent directory does not exist and leave no temp files"],"goal":"verify pkg:npm/write-file-atomic@6.0.0","kind":"HOW","packages":["pkg:npm/write-file-atomic@6.0.0"],"schemaVersion":1,"symbols":["writeFile","writeFile.sync"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/write-file-atomic@6.0.0"],"schemaVersion":1,"subject":"pkg:npm/write-file-atomic@6.0.0","symbols":["writeFile","writeFile.sync"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-write-file-atomic",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-write-file-atomic",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "write-file-atomic": "6.0.0"
      }
    },
    "node_modules/imurmurhash": {
      "version": "0.1.4",
      "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",
      "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==",
      "license": "MIT",
      "engines": {
        "node": ">=0.8.19"
      }
    },
    "node_modules/signal-exit": {
      "version": "4.1.0",
      "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
      "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==",
      "license": "ISC",
      "engines": {
        "node": ">=14"
      },
      "funding": {
        "url": "https://github.com/sponsors/isaacs"
      }
    },
    "node_modules/write-file-atomic": {
      "version": "6.0.0",
      "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-6.0.0.tgz",
      "integrity": "sha512-GmqrO8WJ1NuzJ2DrziEI2o57jKAVIQNf8a18W3nCYU3H7PNWqCCVTeH6/NQE93CIllIgQS98rrmVkYgTX9fFJQ==",
      "license": "ISC",
      "dependencies": {
        "imurmurhash": "^0.1.4",
        "signal-exit": "^4.0.1"
      },
      "engines": {
        "node": "^18.17.0 || >=20.5.0"
      }
    }
  }
}
package.json
{
  "name": "sample-write-file-atomic",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for write-file-atomic",
  "main": "src/index.js",
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "write-file-atomic": "6.0.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/write-file-atomic@6.0.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/write-file-atomic@6.0.0"
  ]
}
src/index.js
'use strict';

const writeFile = require('write-file-atomic');

async function writeAtomic(filename, data, options, callback) {
  return writeFile(filename, data, options, callback);
}

function writeAtomicSync(filename, data, options) {
  return writeFile.sync(filename, data, options);
}

module.exports = {
  writeFile,
  sync: writeFile.sync,
  writeAtomic,
  writeAtomicSync
};
test/contract.mjs
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  writeFile,
  sync,
  writeAtomic,
  writeAtomicSync
} = require('../src/index.js');

async function runContract() {
  const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'csx-write-file-atomic-'));

  try {
    // 1. writeFile atomically writes string and Buffer data asynchronously returning a Promise
    const asyncPath = path.join(tmpDir, 'async-string.txt');
    const promise = writeFile(asyncPath, 'atomic async string');
    assert.ok(promise && typeof promise.then === 'function');
    await promise;
    assert.equal(fs.readFileSync(asyncPath, 'utf8'), 'atomic async string');

    const bufPath = path.join(tmpDir, 'async-buffer.bin');
    const buf = Buffer.from([0x61, 0x74, 0x6f, 0x6d, 0x69, 0x63]);
    await writeAtomic(bufPath, buf);
    assert.deepEqual(fs.readFileSync(bufPath), buf);

    // 2. writeFile supports encoding, mode, fsync, and tmpfileCreated options asynchronously
    const optsPath = path.join(tmpDir, 'async-opts.txt');
    let observedTmpAsync = null;
    await writeFile(optsPath, '68656c6c6f', {
      encoding: 'hex',
      mode: 0o600,
      fsync: false,
      tmpfileCreated(tmpfile) {
        observedTmpAsync = tmpfile;
      }
    });
    assert.equal(fs.readFileSync(optsPath, 'utf8'), 'hello');
    assert.equal(fs.statSync(optsPath).mode & 0o777, 0o600);
    assert.ok(typeof observedTmpAsync === 'string' && observedTmpAsync.startsWith(optsPath));
    assert.equal(fs.existsSync(observedTmpAsync), false);

    // 3. writeFile serializes concurrent writes to the same file and preserves existing mode on overwrite
    const concurrentPath = path.join(tmpDir, 'concurrent.txt');
    await Promise.all([
      writeFile(concurrentPath, 'first', { mode: 0o640 }),
      writeFile(concurrentPath, 'second'),
      writeFile(concurrentPath, 'third')
    ]);
    assert.equal(fs.readFileSync(concurrentPath, 'utf8'), 'third');
    assert.equal(fs.statSync(concurrentPath).mode & 0o777, 0o640);

    // 4. writeFile.sync (and sync export) atomically writes string and Uint8Array data synchronously
    assert.equal(sync, writeFile.sync);
    const syncPath = path.join(tmpDir, 'sync-file.txt');
    let observedTmpSync = null;
    writeAtomicSync(syncPath, 'sync content', {
      encoding: 'utf8',
      mode: 0o600,
      fsync: false,
      tmpfileCreated(tmpfile) {
        observedTmpSync = tmpfile;
      }
    });
    assert.equal(fs.readFileSync(syncPath, 'utf8'), 'sync content');
    assert.equal(fs.statSync(syncPath).mode & 0o777, 0o600);
    assert.ok(typeof observedTmpSync === 'string' && observedTmpSync.startsWith(syncPath));
    assert.equal(fs.existsSync(observedTmpSync), false);

    const u8Path = path.join(tmpDir, 'sync-u8.bin');
    const u8 = new Uint8Array([1, 2, 3, 4]);
    sync(u8Path, u8);
    assert.deepEqual(new Uint8Array(fs.readFileSync(u8Path)), u8);

    // 5. writeFile supports Node-style callback parameter
    const cbPath = path.join(tmpDir, 'callback.txt');
    await new Promise((resolve, reject) => {
      writeFile(cbPath, 'via callback', err => {
        if (err) reject(err);
        else resolve();
      });
    });
    assert.equal(fs.readFileSync(cbPath, 'utf8'), 'via callback');

    // 6. Both async and sync reject/throw when target parent directory does not exist and leave no temp files
    const missingFile = path.join(tmpDir, 'nonexistent-dir', 'file.txt');
    await assert.rejects(() => writeFile(missingFile, 'fail'), { code: 'ENOENT' });
    assert.throws(() => writeFile.sync(missingFile, 'fail'), { code: 'ENOENT' });
  } finally {
    fs.rmSync(tmpDir, { recursive: true, force: true });
  }
}

runContract().catch(err => {
  console.error(err);
  process.exit(1);
});

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

аноним