Skip to content
Related Articles

Related Articles

Improve Article

How to highlight syntax in files using Node.js ?

  • Last Updated : 07 Apr, 2021
Geek Week

Node.js supports modules and packages that can be installed using NPM, which allows us to exploit various functionalities. One such functionality is syntax highlighting using Node.js that helps us to render highlighted code as static HTML, or we can also use it for dynamic syntax highlighting. The following approach covers how to highlight syntax files in Node.js using highlight.js module.

Highlight.js works as a syntax highlighter with automatic language detection. It is written in JavaScript and is supported on the browser as well as on the server.

Module Installation: Use the following command to install highlight.js module using npm from your terminal.

npm install highlight.js

After installing from npm, we can use the package in our code as follows:

const hljs = require('highlight.js');

CDN Import: We can use the following way to import the module on HTML page.



<link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.7.1/styles/default.min.css”>

Example: We have highlighted GeeksForGeeks text in the following example. We have imported highlight.js into our code using CDN and then we have written the desired code into <pre> tag.

HTML




<!DOCTYPE html>
<html lang="en" dir="ltr">
  
<head>
    <meta charset="utf-8">
  
    <!-- Using highlight.js through CDN link -->
    <link rel="stylesheet" href=
  
    <!-- Installing highlight.js through CDN -->
    <script src=
    </script>
</head>
  
<body>
    <pre>
  
        <!-- Here we have used < and > 
        because using angle brackets will be
        interpreted as actual HTML code -->
        <code class="html">
            <strong>GeeksForGeeks</strong>
        </code>
    </pre>
  
    <script type="text/javascript">
  
        // Using highlightAll method to
        // highlight the code
        hljs.highlightAll();
    </script>
</body>
  
</html>

Output:

References: https://highlightjs.org/usage/




My Personal Notes arrow_drop_up
Recommended Articles
Page :