Consume ES Module Libraries from CommonJS Apps By Creating a Simple Node Server

admin  
// simpleServer.mjs

import { createServer } from 'http';
import { parse } from 'url';
import { parse as queryParse } from 'querystring';

const server = createServer((req, res) => {
    const parsedUrl = parse(req.url, true);
    if (parsedUrl.pathname === '/api' && req.method === 'POST') {
        let body = '';
        req.on('data', chunk => {
            body += chunk;
        });
        req.on('end', () => {
            const { urlParam, longString, obj } = queryParse(body);

            // Do something with the received parameters...
            console.log('Received parameters:', { urlParam, longString, obj });

            res.writeHead(200, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ status: 'success' }));
        });
    } else {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('Not Found');
    }
});

server.listen(3000, () => {
    console.log('Server running on http://localhost:3000');
});
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "urlParam=http://example.com&longString=This%20is%20a%20long%20string.&obj={\"key\":\"value\"}" http://localhost:3000/api
// simpleServer.mjs

import { createServer } from 'http';
import { parse } from 'url';
import { parse as queryParse } from 'querystring';

// Mock promise function to simulate asynchronous processing
function processRequestData(data) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (data) {
                resolve({ result: 'Processed successfully!' });
            } else {
                reject(new Error('Failed to process data.'));
            }
        }, 1000);
    });
}

const server = createServer((req, res) => {
    const parsedUrl = parse(req.url, true);
    if (parsedUrl.pathname === '/api' && req.method === 'POST') {
        let body = '';
        req.on('data', chunk => {
            body += chunk;
        });
        req.on('end', () => {
            const { urlParam, longString, obj } = queryParse(body);

            // Use the promise function to process data
            processRequestData({ urlParam, longString, obj })
                .then(responseData => {
                    res.writeHead(200, { 'Content-Type': 'application/json' });
                    res.end(JSON.stringify(responseData));
                })
                .catch(error => {
                    res.writeHead(500, { 'Content-Type': 'application/json' });
                    res.end(JSON.stringify({ error: error.message }));
                });
        });
    } else {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('Not Found');
    }
});

server.listen(3000, () => {
    console.log('Server running on http://localhost:3000');
});
// commonjsApp.js (CommonJS)

const http = require('http');
const querystring = require('querystring');

function consumeAPI(urlParam, longString, obj) {
    const postData = querystring.stringify({
        urlParam,
        longString,
        obj: JSON.stringify(obj)
    });

    const options = {
        hostname: 'localhost',
        port: 3000,
        path: '/api',
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': Buffer.byteLength(postData)
        }
    };

    const req = http.request(options, res => {
        res.setEncoding('utf8');
        let responseBody = '';
        res.on('data', chunk => {
            responseBody += chunk;
        });
        res.on('end', () => {
            console.log('API response:', responseBody);
        });
    });

    req.on('error', error => {
        console.error(`Request error: ${error.message}`);
    });

    req.write(postData);
    req.end();
}

// Example usage:
consumeAPI('http://example.com', 'This is a long string.', { key: 'value' });

Consume ES Module Libraries from CommonJS Apps By Creating a Simple Node Server

If you want to use ES Module Libraries from CommonJS Apps or you endup in a version or depdency hell, or even want to use nodejs libraries from other languanges like python you can easily expose them as APIs

Consume ES Module Libraries from CommonJS Apps By Creating a Simple Node Server

If you want to use ES Module Libraries from CommonJS Apps or you endup in a version or depdency hell, or even want to use nodejs libraries from other languanges like python you can easily expose them as APIs

Converting a Database From Mysql to Sqlite

Check how to convert a database from MySql to Sqlite using mysql2sqlite and a docker container with MySQL and Adminer