🌐
npm
npmjs.com › package › parse-prometheus-text-format
parse-prometheus-text-format - npm
August 12, 2019 - Parses Prometheus text format into JavaScript objects. Latest version: 1.1.1, last published: 7 years ago. Start using parse-prometheus-text-format in your project by running `npm i parse-prometheus-text-format`. There are 20 other projects ...
      » npm install parse-prometheus-text-format
    
Published: Aug 12, 2019
Version: 1.1.1
Author: Yunyu Lin
🌐
GitHub
github.com › SieDeta › prometheus-parser
GitHub - SieDeta/prometheus-parser · GitHub
Prometheus will now be reachable at http://localhost:9090/. ... Go version 1.17 or greater. NodeJS version 16 or greater.
Author: SieDeta
🌐
Medium
medium.com › @texasdave2 › the-best-little-parsing-prometheus-textfile-exporter-shell-script-template-ever-9349b7ea7988
The best little parsing prometheus textfile exporter shell script template ever! | by David O'Dell | Medium
March 4, 2020 - Learn how to use this simple rock solid script to turn common database queries into usable prometheus friendly metrics and get them into node exporter.
🌐
DEV Community
dev.to › oluwatobi2001 › optimizing-performance-using-prometheus-with-node-js-for-monitoring-b90
Optimizing Performance Using Prometheus with Node JS for Monitoring - DEV Community
April 30, 2024 - Its Alert features also notify the application developer in case of an occurrence of any anomaly in the application metrics. Additionally; it possesses an advanced feature known as the PROMQL (Prometheus query language) which allows the developer to use advanced queries to generate data commands for appropriate analysis and the generation of measurable information insights.
🌐
npm
npmjs.com › package › prometheus
prometheus - npm
Prometheus is a simple ODM for Node.js with adapter for MongoDB (so far) and built-in form builder, form parser, and table builder.
      » npm install prometheus
    
Published: Nov 21, 2013
Version: 0.1.7
🌐
npm
npmjs.com › package › prometheus-query
prometheus-query - npm
September 14, 2025 - A Javascript client for Prometheus query API. Latest version: 3.5.1, last published: a year ago. Start using prometheus-query in your project by running `npm i prometheus-query`. There are 18 other projects in the npm registry using prometheus-query.
      » npm install prometheus-query
    
Published: Sep 14, 2025
Version: 3.5.1
🌐
Medium
tohidhaghighi.medium.com › add-prometheus-metrics-in-nodejs-ce0ff5a43b44
Add Prometheus metrics in Nodejs. Prometheus is an open-source technology… | by Tohid haghighi | Medium
October 16, 2023 - The Prometheus server collects metrics from your servers and other monitoring targets by pulling their metric endpoints over HTTP at a predefined time interval. For ephemeral and batch jobs, for which metrics can’t be scraped periodically due to their short-lived nature, Prometheus offers a Push gateway.
🌐
Better Stack
betterstack.com › community › guides › scaling-nodejs › nodejs-prometheus
Monitoring Node.js Apps with Prometheus | Better Stack Community
Learn how to leverage Prometheus for monitoring the performance, health, and behavior of your Node.js applications
Starred by 39 users
Forked by 14 users
Languages: JavaScript 100.0% | JavaScript 100.0%
Top answer
1 of 1
24

There's a nice package already available to do that and it's by the Prometheus's Authors itself.

They have written a bunch of Go libraries that are shared across Prometheus components and libraries. They are considered internal to Prometheus but you can use them.

Refer: github.com/prometheus/common doc. There's a package called expfmt that can decode and encode the Prometheus's Exposition Format (Link). Yes, it follows the EBNF syntax so ebnf package could also be used but you're getting expfmt right out of the box.

Package used: expfmt

Sample Input:

# HELP net_conntrack_dialer_conn_attempted_total
# TYPE net_conntrack_dialer_conn_attempted_total untyped
net_conntrack_dialer_conn_attempted_total{dialer_name="federate",instance="localhost:9090",job="prometheus"} 1 1608520832877

Sample Program:

package main

import (
    "flag"
    "fmt"
    "log"
    "os"

    dto "github.com/prometheus/client_model/go"
    "github.com/prometheus/common/expfmt"
)

func fatal(err error) {
    if err != nil {
        log.Fatalln(err)
    }
}

func parseMF(path string) (map[string]*dto.MetricFamily, error) {
    reader, err := os.Open(path)
    if err != nil {
        return nil, err
    }

    var parser expfmt.TextParser
    mf, err := parser.TextToMetricFamilies(reader)
    if err != nil {
        return nil, err
    }
    return mf, nil
}

func main() {
    f := flag.String("f", "", "set filepath")
    flag.Parse()

    mf, err := parseMF(*f)
    fatal(err)

    for k, v := range mf {
        fmt.Println("KEY: ", k)
        fmt.Println("VAL: ", v)
    }
}

Sample Output:

KEY:  net_conntrack_dialer_conn_attempted_total
VAL:  name:"net_conntrack_dialer_conn_attempted_total" type:UNTYPED metric:<label:<name:"dialer_name" value:"federate" > label:<name:"instance" value:"localhost:9090" > label:<name:"job" value:"prometheus" > untyped:<value:1 > timestamp_ms:1608520832877 >

So, expfmt is a good choice for your use-case.

Update: Formatting problem in OP's posted input:

Refer:

  1. https://github.com/prometheus/pushgateway/issues/147#issuecomment-368215305

  2. https://github.com/prometheus/pushgateway#command-line

Note that in the text protocol, each line has to end with a line-feed
character (aka 'LF' or '\n'). Ending a line in other ways, e.g. with 
'CR' aka '\r', 'CRLF' aka '\r\n', or just the end of the packet, will
result in a protocol error.

But from the error message, I could see \r char is present in in the put which is not acceptable by design. So use \n for line endings.

Find elsewhere
🌐
GitHub
github.com › siimon › prom-client
GitHub - prometheus/client_js: Prometheus client for node.js · GitHub
See example folder for a sample usage. The library does not bundle any web framework. To expose the metrics, respond to Prometheus's scrape requests with the result of await registry.metrics().
Author: prometheus
🌐
Stack Overflow
stackoverflow.com › questions › 66059132 › parse-prometheus-metrics-data-to-add-label-and-re-parse-to-prometheus-metrics-fo
parsing - Parse prometheus metrics data to add label and re-parse to prometheus metrics format - Stack Overflow
package main import ( "flag" "fmt" "log" "os" dto "github.com/prometheus/client_model/go" "github.com/prometheus/common/expfmt" ) func fatal(err error) { if err != nil { log.Fatalln(err) } } func parseMF(path string) (map[string]*dto.MetricFamily, error) { reader, err := os.Open(path) if err != nil { return nil, err } var parser expfmt.TextParser mf, err := parser.TextToMetricFamilies(reader) if err != nil { return nil, err } return mf, nil } func main() { f := flag.String("f", "", "set filepath") flag.Parse() mf, err := parseMF(*f) fatal(err) for k, v := range mf { fmt.Println("KEY: ", k) fmt.Println("VAL: ", v) } }
🌐
Prometheus
prometheus.io › docs › instrumenting › clientlibs
Client libraries | Prometheus
Before you can monitor your services, you need to add instrumentation to their code via one of the Prometheus client libraries.
Top answer
1 of 5
9

I believe you can.

The blogposts I have linked below detail how this is done using the Prometheus Python client to ingest metrics in JSON format into Prometheus.

https://www.robustperception.io/writing-a-jenkins-exporter-in-python/ https://www.robustperception.io/writing-json-exporters-in-python/

2 of 5
5

I was able to find a solution using the prom-client and building my own custom metric. Will provide an example below for anyone who may be interested in doing the same. Let's say that there is a health check endpoint that returns the following JSON:

{
    "app": {
        "message": "Service is up and running!",
        "success": true
    }
}

I used the package request to make a call to the endpoint, parse the data and create a gauge to reflect a value based on the health check status. Below is an example of the /metrics endpoint in JavaScript:

const express = require('express');
const router = express.Router();
const request = require('request');

// Config for health check endpoint
const healthCheckURL = 'https://SOME_ENDPOINT/health';
const zone = 'DEV';

// Initialize Prometheus
const Prometheus = require('prom-client');
const collectDefaultMetrics = Prometheus.collectDefaultMetrics;
collectDefaultMetrics({
    timeout: 5000
});

router.get('/', (req, res) => {
    res.end(Prometheus.register.metrics());
});

const serviceHealthGauge = new Prometheus.Gauge({
    name: 'service_health',
    help: 'Health of service component',
    labelNames: ['zone']
});

setInterval(() => {
    request({
            url: healthCheckURL,
            method: "GET",
        },
        function(error, response, body) {
            if (!error && response.statusCode == 200) {
                const JSONBody = JSON.parse(body);

                // check service health
                if (JSONBody.app && JSONBody.app.success) {
                    serviceHealthGauge.set({
                        zone: zone
                    }, 1);
                } else {
                    serviceHealthGauge.set({
                        zone: zone
                    }, 0);

                }
            } else {
                serviceHealthGauge.set({
                    zone: zone
                }, 0);
            }
        }   
    );
  }, 10000);

module.exports.metricNames = ['service_health'];

module.exports = router;
🌐
Coder Society
codersociety.com › blog › articles › nodejs-application-monitoring-with-prometheus-and-grafana
Node.js Application Monitoring with Prometheus and Grafana, — Coder Society
It provides the building blocks to export metrics to Prometheus via the pull and push methods and supports all Prometheus metric types such as histogram, summaries, gauges and counters. Create a new directory and setup the Node.js project: $ mkdir example-nodejs-app $ cd example-nodejs-app $ npm init -y
🌐
Medium
mehranjnf.medium.com › developing-a-metric-endpoint-in-node-js-for-prometheus-a28710e6483a
Designing a Node.js Metrics Endpoint for Prometheus | by Mehran | Medium
May 3, 2023 - Now it’s time to query the collected metrics in Prometheus. To do this, navigate to the Graph menu and enter the following text in the expression text box. This represents the custom metric the service gathers when a call is made to the /hello endpoint. In addition to this metric, the prom-client automatically collects numerous other metrics.
🌐
Craftsman Nadeem
reachmnadeem.wordpress.com › 2021 › 02 › 11 › instrumenting-nodejs-express-applications-for-prometheus-metrics
Instrumenting NodeJs Express Applications For Prometheus Metrics | Craftsman Nadeem
February 12, 2021 - NodeJs Application Create Folder mkdir nodejs-prometheus cd nodejs-prometheus create package.json npm init --yes install dev dependencies npm install -D babel-cli babel-preset-env nodemon npm-run-all rimraf pino-pretty install prod dependencies npm install -P cors dotenv express prom-client pino express-pino-logger script "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "clean": "rimraf ./dist/", "build": "babel ./src/…
🌐
Go Packages
pkg.go.dev › github.com › prometheus › prometheus › promql › parser
parser package - github.com/prometheus/prometheus/promql/parser - Go Packages
github.com/prometheus/prometheus · Open Source Insights · Code Wiki · Code generated by goyacc -l -o promql/parser/generated_parser.y.go promql/parser/generated_parser.y. DO NOT EDIT. Constants · Variables · func ChildrenIter(node Node) func(func(Node) bool) func DocumentedType(t ValueType) string ·
🌐
Devon Burriss' Blog
devonburriss.me › prometheus-parser-fennel
Creating a Prometheus parser: Fennel - Devon Burriss' Blog
December 24, 2020 - It can parse Prometheus text to objects, and turn these metric objects into valid Prometheus text. This was my first time using a library to do a custom parser. In the past when I had needed to parse text I had used a state machine and consumed a character at a time.
🌐
SquaredUp
squaredup.com › home › blog › instrumenting node.js code with prometheus custom metrics
Instrument Node.js code: Prometheus custom metrics - SquaredUp
February 27, 2023 - How to instrument your Node.js code with custom Prometheus metrics using the prom-client package. Get a full walk through here