1 minute read

fs already contains promisified API that doesn’t need promisify.

const fsPromises = require("fs/promises");
await fsPromises.writeFile(file, data[, options])

Asynchronous promise-based version requires to use it as a part of promise-based control flow, while synchronous version doesn’t impose this requirement.

Asynchronous readFile/writeFile is non-blocking, while synchronous readFileSync/writeFileSync is blocking but allows to complete a job faster. This may be noticeable during intensive IO operations.

fs.readFile takes a callback function, which means it will not block the execution of your script. fs.readFileSync however does not take a callback, which means that the execution of your script will be paused untill the process is finished. Using promisfy is one way to solve this issue, for small files it wont make a difference, but for large files you might want to transform fs.readFileSync into a promise so you wont block the execution.


import { promises as fs } from "node:fs";

// Записать строку в файл
await fs.writeFile("output.txt", "Some content", "utf8");

// Записать JSON в файл
const data = { key: "value" };
await fs.writeFile("output.json", JSON.stringify(data, null, 2), "utf8");

// Добавить содержимое в конец файла
await fs.appendFile("log.txt", "New log entry\n", "utf8");

Файл будет создан в текущей рабочей директории. Если нужен полный путь, используйте:

import { join } from "path";

const outputPath = join(__dirname, "test-results.json");
await fs.writeFile(outputPath, JSON.stringify(data, null, 2), "utf8");

writeFileSync

Если вы хотите использовать синхронный вариант записи в файл, нужно импортировать fs (не promises версию) и использовать writeFileSync. Вот как это сделать:

import fs from "node:fs"; // Изменить импорт на обычный fs
// ...existing code...

async function clickByText(page, text) {
  // ...existing code...
  if (element) {
    const elementInfo = {
      timestamp: new Date().toISOString(),
      element: {
        tagName: element.tagName,
        text: element.text,
        className: element.className,
      },
    };

    fs.writeFileSync("test-results.json", JSON.stringify(elementInfo, null, 2), "utf8");

    // ...existing code...
  }
}

Преимущество writeFileSync в том, что он блокирует выполнение кода до завершения записи, и не требует await. Однако в большинстве случаев рекомендуется использовать асинхронную версию, чтобы не блокировать основной поток выполнения.