code-block-language-detector
v1.0.6
Published
Detects the programming language of code snippets
Downloads
320
Maintainers
Readme
Code Block Language Detector
A lightweight Node.js package to detect the programming language of a given code snippet. Built on top of highlight.js, it supports a wide range of programming languages.
Features
- Detects programming language from code snippets.
- Supports popular languages like JavaScript, Python, C++, Java, and more.
- Option to restrict detection to specific languages for better accuracy.
- Lightweight and easy to integrate.
Installation
Install the package via npm:
npm install code-block-language-detector
Usage
Basic Usage
Detect the programming language of a given code snippet:
const detectLanguage = require("code-block-language-detector");
const code = `const x = 42; console.log(x);`;
const language = detectLanguage(code);
console.log(language); // Output: 'javascript'
Restricting to Specific Languages
const detectLanguage = require("code-block-language-detector");
const code = `SELECT * FROM users WHERE age > 21;`;
const language = detectLanguage(code, ["sql", "javascript", "python"]);
console.log(language); // Output: 'sql'
Error Handling
If the provided code snippet is invalid or detection fails, the function returns "unknown":
const code = `+++---===`;
const language = detectLanguage(code);
console.log(language); // Output: 'unknown'
Supported Languages
The following languages are currently supported:
- JavaScript
- Python
- Java
- C
- C++
- Ruby
- PHP
- TypeScript
- Go
- Swift
- Kotlin
- Rust
- C#
- HTML
- CSS
- JSON
- YAML
- Bash
- SQL
- Perl
- R
- Dart
- Scala
- Shell