Clang Format Node Wrapper

3.0.2 · active · verified Tue Apr 21

clang-format-node is a Node.js wrapper that provides programmatic access to the LLVM project's `clang-format` and `git-clang-format` native binaries. The current stable version is 3.0.2, bundling LLVM clang-format version 22.1.3. This package securely builds and bundles these native binaries directly from official LLVM source code, eliminating third-party binary dependencies and offering full GitHub Actions Attestation and npm Build Provenances for enhanced supply chain security. It also includes separate packages within its monorepo, `clang-format-git` for standalone Git integration without Python, and `clang-format-git-python` for the original Python script wrapper. Release cycles typically align with new LLVM clang-format versions, ensuring access to the latest formatting capabilities and bug fixes. It is inspired by `angular/clang-format` but aims for a more streamlined and secure integration into Node.js and npm workflows.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to import and use the asynchronous `format` function to apply `clang-format` styling to a C++ code string using different style presets. It includes error handling for formatting failures.

import { format } from 'clang-format-node';

async function applyFormatting() {
  const code = `#include <iostream>\n\nint main() { std::cout << "Hello, World!" << std::endl; return 0; }\n`;
  try {
    // Formats the C++ code string using the 'Google' style
    // 'fallbackStyle' ensures a default is used if 'style' isn't recognized or available.
    const formattedCode = await format(code, { 
      style: 'Google', 
      fallbackStyle: 'LLVM'
    });
    console.log('Original Code:\n', code);
    console.log('Formatted Code (Google Style):\n', formattedCode);

    // Example of formatting with a different style (e.g., 'Mozilla')
    const anotherFormattedCode = await format(code, { 
      style: 'Mozilla', 
      fallbackStyle: 'LLVM'
    });
    console.log('Formatted Code (Mozilla Style):\n', anotherFormattedCode);

  } catch (error) {
    console.error('Failed to format code:', error);
    // Specific error handling for clang-format issues
    if (error instanceof Error && error.message.includes('clang-format failed')) {
        console.error('The clang-format binary returned an error. Check input or style options.');
    }
  }
}

applyFormatting();

view raw JSON →