Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including filename2prism with all npm packages installed. Try it out:

var filename2prism = require("filename2prism")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

filename2prism v1.0.1

Converts source code filenames to PrismJS language aliases.

filename2prism

NPM version JavaScript Style Guide

Converts source code filenames to PrismJS language aliases.

Install

Install with npm:

$ npm i filename2prism --save

Usage

The following reads a directory of source code files, highlights them according to their filenames, and then outputs the results to another directory:

const path = require('path')
const fs = require('fs')

const filename2prism = require('filename2prism')
const prism = require('prismjs')
require('prismjs/components/')() // Loads all languages

const src = 'path/to/some/src/dir'
const out = 'path/to/some/out/dir'

fs.readdirSync(src)
  .filter(name => fs.statSync(path.join(src, name)).isFile())
  .forEach(name => {
    let alias = filename2prism(name)

    if (typeof alias === 'undefined') {
      throw new Error('No matching language found from filename!')
    }

    if (Array.isArray(alias)) {
      // Multiple matches found, picked first one for simplicity
      alias = alias[0]
    } // else one match was found

    fs.writeFileSync(
      path.join(out, name),
      prism.highlight(
        fs.readFileSync(path.join(src, name)).toString(),
        prism.languages[alias],
        alias
      )
    )
  })

Method

filename2prism(filename) -> string | Array<string> | undefined

Returns a PrismJS language alias from a filename. A string is returned if there was one match, an Array<string> is returned if there were multiple matches, and undefined is returned if there was no match.

Parameters:

  • filename : string - The filename to infer a PrismJS alias from.

Related

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.

Running Tests

Install dev dependencies:

$ npm i -d && npm test

Author

Tomer Aberbach

License

Copyright © 2018 Tomer Aberbach Released under the MIT license.

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free