DEV Community

Lorenzo Tomazzoni
Lorenzo Tomazzoni

Posted on

JS SERVER NOT WORKING WITH JARS

Question:
I have two versions of a server using express.js. The first version should create a .zip file containing two .JAR files (Client.jar and Server.jar) but when I try to connect, it says "Cannot connect to the server".

The second version simply creates a .zip with the .JAVA files, and it works perfectly.

How can I modify the first version so that it works and successfully creates a .zip containing the .JAR files?

First Version (Not Working - Attempts to generate .JAR files):
javascript
Copia codice
const express = require('express');
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const archiver = require('archiver');
const { exec } = require('child_process');

const app = express();
app.use(cors());
app.use(express.json());

app.post('/generate-files', (req, res) => {
const { ip, port } = req.body;

const clientFilePath = path.join(__dirname, 'Client.java');
const serverFilePath = path.join(__dirname, 'Server.java');

let clientFileContent = fs.readFileSync(clientFilePath, 'utf-8');
let serverFileContent = fs.readFileSync(serverFilePath, 'utf-8');

// Replace IP and port
clientFileContent = clientFileContent.replace('127.0.0.1', ip).replace('12345', port);
serverFileContent = serverFileContent.replace('12345', port);

const tempDir = path.join(__dirname, 'temp');
fs.mkdirSync(tempDir, { recursive: true });

// Write modified files to the temp directory
const tempClientPath = path.join(tempDir, 'Client.java');
const tempServerPath = path.join(tempDir, 'Server.java');
fs.writeFileSync(tempClientPath, clientFileContent);
fs.writeFileSync(tempServerPath, serverFileContent);

// Compile Java files
exec(`javac ${tempClientPath} ${tempServerPath}`, (err, stdout, stderr) => {
    if (err) {
        console.error('Compilation Error:', stderr);
        res.status(500).send('Error compiling Java files.');
        return;
    }

    // Create JAR files
    const clientJarPath = path.join(tempDir, 'Client.jar');
    const serverJarPath = path.join(tempDir, 'Server.jar');

    exec(`jar cfe ${clientJarPath} Client -C ${tempDir} Client.class`, (err) => {
        if (err) {
            console.error('Error creating Client.jar:', err);
            res.status(500).send('Error creating Client.jar.');
            return;
        }

        exec(`jar cfe ${serverJarPath} Server -C ${tempDir} Server.class`, (err) => {
            if (err) {
                console.error('Error creating Server.jar:', err);
                res.status(500).send('Error creating Server.jar.');
                return;
            }

            // Create ZIP archive
            const output = fs.createWriteStream(path.join(__dirname, 'files.zip'));
            const archive = archiver('zip', { zlib: { level: 9 } });

            output.on('close', () => {
                res.download(path.join(__dirname, 'files.zip'), 'files.zip', () => {
                    fs.rmSync(tempDir, { recursive: true, force: true });
                    fs.unlinkSync(path.join(__dirname, 'files.zip'));
                });
            });

            archive.pipe(output);
            archive.file(clientJarPath, { name: 'Client.jar' });
            archive.file(serverJarPath, { name: 'Server.jar' });
            archive.finalize();
        });
    });
});
Enter fullscreen mode Exit fullscreen mode

});

// Start server on port 3000
app.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});

Here is the formatted version of your question and code for Stack Overflow:

Question:
I have two versions of a server using express.js. The first version should create a .zip file containing two .JAR files (Client.jar and Server.jar) but when I try to connect, it says "Cannot connect to the server".

The second version simply creates a .zip with the .JAVA files, and it works perfectly.

How can I modify the first version so that it works and successfully creates a .zip containing the .JAR files?

First Version (Not Working - Attempts to generate .JAR files):
javascript
Copia codice
const express = require('express');
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const archiver = require('archiver');
const { exec } = require('child_process');

const app = express();
app.use(cors());
app.use(express.json());

app.post('/generate-files', (req, res) => {
const { ip, port } = req.body;

const clientFilePath = path.join(__dirname, 'Client.java');
const serverFilePath = path.join(__dirname, 'Server.java');

let clientFileContent = fs.readFileSync(clientFilePath, 'utf-8');
let serverFileContent = fs.readFileSync(serverFilePath, 'utf-8');

// Replace IP and port
clientFileContent = clientFileContent.replace('127.0.0.1', ip).replace('12345', port);
serverFileContent = serverFileContent.replace('12345', port);

const tempDir = path.join(__dirname, 'temp');
fs.mkdirSync(tempDir, { recursive: true });

// Write modified files to the temp directory
const tempClientPath = path.join(tempDir, 'Client.java');
const tempServerPath = path.join(tempDir, 'Server.java');
fs.writeFileSync(tempClientPath, clientFileContent);
fs.writeFileSync(tempServerPath, serverFileContent);

// Compile Java files
exec(`javac ${tempClientPath} ${tempServerPath}`, (err, stdout, stderr) => {
    if (err) {
        console.error('Compilation Error:', stderr);
        res.status(500).send('Error compiling Java files.');
        return;
    }

    // Create JAR files
    const clientJarPath = path.join(tempDir, 'Client.jar');
    const serverJarPath = path.join(tempDir, 'Server.jar');

    exec(`jar cfe ${clientJarPath} Client -C ${tempDir} Client.class`, (err) => {
        if (err) {
            console.error('Error creating Client.jar:', err);
            res.status(500).send('Error creating Client.jar.');
            return;
        }

        exec(`jar cfe ${serverJarPath} Server -C ${tempDir} Server.class`, (err) => {
            if (err) {
                console.error('Error creating Server.jar:', err);
                res.status(500).send('Error creating Server.jar.');
                return;
            }

            // Create ZIP archive
            const output = fs.createWriteStream(path.join(__dirname, 'files.zip'));
            const archive = archiver('zip', { zlib: { level: 9 } });

            output.on('close', () => {
                res.download(path.join(__dirname, 'files.zip'), 'files.zip', () => {
                    fs.rmSync(tempDir, { recursive: true, force: true });
                    fs.unlinkSync(path.join(__dirname, 'files.zip'));
                });
            });

            archive.pipe(output);
            archive.file(clientJarPath, { name: 'Client.jar' });
            archive.file(serverJarPath, { name: 'Server.jar' });
            archive.finalize();
        });
    });
});
Enter fullscreen mode Exit fullscreen mode

});

// Start server on port 3000
app.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
Second Version (Working - Generates .zip with .JAVA files):
javascript
Copia codice
const express = require('express');
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const archiver = require('archiver');

const app = express();
app.use(cors());
app.use(express.json());

app.post('/generate-files', (req, res) => {
const { ip, port } = req.body;

const clientFilePath = path.join(__dirname, 'Client.java');
const serverFilePath = path.join(__dirname, 'Server.java');

let clientFileContent = fs.readFileSync(clientFilePath, 'utf-8');
let serverFileContent = fs.readFileSync(serverFilePath, 'utf-8');

// Replace IP and port
clientFileContent = clientFileContent.replace('127.0.0.1', ip).replace('12345', port);
serverFileContent = serverFileContent.replace('12345', port);

const tempDir = path.join(__dirname, 'temp');
fs.mkdirSync(tempDir, { recursive: true });

fs.writeFileSync(path.join(tempDir, 'Client.java'), clientFileContent);
fs.writeFileSync(path.join(tempDir, 'Server.java'), serverFileContent);

const output = fs.createWriteStream(path.join(__dirname, 'files.zip'));
const archive = archiver('zip', { zlib: { level: 9 } });

output.on('close', () => {
    res.download(path.join(__dirname, 'files.zip'), 'files.zip', () => {
        fs.rmSync(tempDir, { recursive: true, force: true });
        fs.unlinkSync(path.join(__dirname, 'files.zip'));
    });
});

archive.pipe(output);
archive.directory(tempDir, false);
archive.finalize();
Enter fullscreen mode Exit fullscreen mode

});

// Start server on port 3000
app.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
What I Need:
I want the first version to work so that it can generate a .zip file containing the two .JAR files instead of the .JAVA files. How can I fix it?****

Top comments (0)