Javascript library to allow reading of a PGN (Portable Game Notation) chess game notation, and providing the result as JSON.
PGN is a shortcut for portable game notation. It was developed in 1993. It helps standardize how chess games were notated, so that computer programs like the PgnViewerJS could be developed. PGN is the standard to keep chess games forever. There are huge databases available like those from https://lichess.org.
Everyone that wants to implement chess software and has to read PGN notation. The library is a runtime component to be included in the usual way.
import { parser } from '@mliebelt/pgn-parser'
or
let parser = require("@mliebelt/pgn-parser").parser
npm i @mliebelt/pgn-parser --save
- Run build.sh
- Add pgn-bundle.js to your app bundle
- Execute
parse
function via JavascriptCore
struct PGNParser {
func parse(string: String) {
guard let bundle = Bundle.main.path(forResource: "pgn-bundle", ofType: "js") else { return }
do {
let source = try String(contentsOfFile: bundle)
let context = JSContext()
context?.exceptionHandler = { context, exception in
if let exceptionString = exception?.toString() {
debugPrint("Error parsing PGN: \(exceptionString)")
}
}
let window = JSValue(newObjectIn: context)
context?.setObject(window, forKeyedSubscript: "window" as NSString)
context?.evaluateScript(source)
context?.evaluateScript(source)
let parseFunction = window?.objectForKeyedSubscript("parsePgn")
let options = ["startRule": "game"]
let result = parseFunction?.call(withArguments: [string, options])
print(result?.toDictionary() ?? [:])
} catch {
debugPrint("Error parsing PGN: \(error)")
return
}
}
}
// Usage:
let parser = PGNParser()
parser.parse("pgn text")
Look at the many test cases that show how to use it. Here is an example:
const fs = require('fs/promises')
const path = require('path')
const {splitter, parser} = require('@mliebelt/pgn-parser')
// helpers
const parseGames = (string) => parser.parse(string, {startRule: 'games'})
const splitGames = (string) => splitter.split(string, {startRule: "games"})
// assuming source directory is sibling of node_modules
const gameFilePath = path.resolve(__dirname, '../node_modules/@mliebelt/pgn-parser/sampleGame.pgn')
fs.readFile(gameFilePath, 'utf-8')
.then(pgnFile=> {
const game = parseGames(pgnFile).pop()
console.log('game.moves[0] = ', game.moves[0])
})
.catch(console.error)
// assuming source directory is sibling of node_modules
const gamesFilePath = path.resolve(__dirname, '../node_modules/@mliebelt/pgn-parser/sampleGames.pgn')
fs.readFile(gamesFilePath, 'utf-8')
.then(pgnFile=> {
const games = splitGames(pgnFile)
const players = []
games.forEach((game) => {
const tags = parser.parse(game.tags, {startRule: 'tags'})
players.push(tags.White)
players.push(tags.Black)
})
console.log('Games: ', JSON.stringify(games, null, 2))
console.log('Players: ', JSON.stringify(players, null, 2))
})
.catch(console.error)
It does not have an API, just a JSON structure that has to be read then. You have 4 top level rules to use the parser:
games
: Reads many games from the string given, returns an array of games (object with keystags
andmoves
).game
: Reads a complete game, and returns an object with keystags
andmoves
.tags
: Reads only the tags from the given input. The input must not contain any moves.pgn
: Reads only the moves of the game (as array).
A code example to read a complete game then looks like:
import parser from '@mliebelt/pgn-parser'
let game = parser.parse('[White "Me"] [Black "Magnus"] 1. f4 e5 2. g4 Qh4#', {startRule: "game"})
console.log(JSON.stringify(res, null, 2))
==>
JSON.stringify(res, null, 2)
{
"tags": {
"White": "Me",
"Black": "Magnus"
},
"moves": [
{
"turn": "w",
"moveNumber": 1,
...
},
{...},
...
]
}
If you want to use the library in the browser, the above method will not work. In the ticket 22, Bebul explained how to do it. Here is the complete recipe:
-
Install Browserify.
-
Store the parse function as window property
File: parsePgn.js ---- const parser = require('./pgn-parser.js') window.parsePgn = parser.parse
-
Process newly created parsePgn.js through Browserify.
browserify parsePgn.js -o pgn-bundle.js
-
In the
index.html
then use:<script type="text/javascript" src="pgn/pgn-bundle.js"></script>
-
And the parsePgn is now available:
let gameList = parsePgn('[White "Me"] [Black "Magnus"] 1. f4 e5 2. g4 Qh4#', {startRule: "game"});
- peggy Parser Generator implemented in Javascript. Used for regenerating the javascript library completely by an automatic build.
- PGN Specification: PGN (Portable Game Notation) specification, there the section 8.2. Most other parts of the spec are implemented as well.
- PGN Supplement Additional specification for adding structured comments, like circles, arrows and clock annotations.
- NAG Specification Definition of the NAGs (Numeric Annotation Glyphs)