To call the pandoc/core
Docker image from a Node.js Express application, you can use the dockerode
library, which is a Docker client for Node.js. This allows you to interact with Docker from within your Node.js application. Below is an example of how you can set this up.
Step-by-Step Guide
Install Required Packages:
First, create a new Node.js project and install the necessary packages.mkdir pandoc-express cd pandoc-express npm init -y npm install express dockerode body-parser
Set Up the Express Application:
Create an Express application inapp.js
with endpoints to handle document conversions.// app.js const express = require('express'); const bodyParser = require('body-parser'); const Docker = require('dockerode'); const fs = require('fs'); const path = require('path'); const app = express(); const docker = new Docker(); app.use(bodyParser.json()); // Endpoint to convert Markdown to PDF app.post('/convert', (req, res) => { const { inputMarkdown, outputFormat } = req.body; const inputFilePath = path.join(__dirname, 'input.md'); const outputFilePath = path.join(__dirname, `output.${outputFormat}`); // Write the input Markdown to a file fs.writeFileSync(inputFilePath, inputMarkdown); // Run the pandoc Docker container docker.run('pandoc/core', ['-f', 'markdown', '-t', outputFormat, '/data/input.md', '-o', `/data/output.${outputFormat}`], process.stdout, { Binds: [`${__dirname}:/data`] }, (err, data, container) => { if (err) { return res.status(500).send(err); } // Read the output file fs.readFile(outputFilePath, (err, data) => { if (err) { return res.status(500).send(err); } res.setHeader('Content-Disposition', `attachment; filename=output.${outputFormat}`); res.send(data); // Clean up the files fs.unlinkSync(inputFilePath); fs.unlinkSync(outputFilePath); }); }); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
Run the Express Application:
Start the Express application using Node.js.node app.js
Make a Request to the Endpoint:
You can use a tool likecurl
, Postman, or an HTTP client in your browser to make a POST request to the/convert
endpoint.Example using
curl
:curl -X POST http://localhost:3000/convert \ -H "Content-Type: application/json" \ -d '{"inputMarkdown": "# Hello World", "outputFormat": "pdf"}' \ --output output.pdf
Explanation
- Dependencies: The
express
package is used to create the web server,dockerode
to interact with Docker, andbody-parser
to parse JSON request bodies. - Docker Container: The Docker container is run with the
pandoc/core
image to convert the Markdown file to the desired output format. - File Handling: The input Markdown is written to a file in the server directory, and the output file is read back after conversion. Both files are cleaned up after the response is sent.
This setup allows your Express application to leverage the pandoc/core
Docker image to convert documents dynamically.