DEV Community

Mohammad Reza Omrani
Mohammad Reza Omrani

Posted on

Document Content Save Button

public/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Example .myext Editor</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }
    textarea {
      width: 100%;
      height: 300px;
    }
    button {
      margin-top: 10px;
    }
  </style>
</head>
<body>
  <h1>Edit example.myext File</h1>
  <textarea id="fileContent"></textarea>
  <button onclick="saveChanges()">Save Changes</button>
  <script>
    // Fetch the content of the .myext file and display it
    fetch('/example.myext')
      .then(response => response.text())
      .then(data => {
        document.getElementById('fileContent').value = data;
      });

    // Save changes made to the .myext file
    function saveChanges() {
      const content = document.getElementById('fileContent').value;
      fetch('/example.myext', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ content: content })
      })
      .then(response => response.text())
      .then(data => {
        alert('File saved successfully');
      })
      .catch(err => {
        alert('Error saving file');
      });
    }
  </script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

server.js

const express = require('express');
const app = express();
const fs = require('fs');
const path = require('path');

// Serve static files
app.use(express.static('public'));

// Route to fetch .myext file content
app.get('/example.myext', (req, res) => {
  const filePath = path.join(__dirname, 'example.myext');
  fs.readFile(filePath, 'utf8', (err, data) => {
    if (err) {
      return res.status(500).send('Error loading .myext file');
    }
    res.send(data); // Send the content of the .myext file
  });
});

// Serve the main HTML page
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.post('/example.myext', (req, res) => {
    let body = '';
    req.on('data', chunk => {
      body += chunk;
    });

    req.on('end', () => {
      const data = JSON.parse(body);
      const filePath = path.join(__dirname, 'example.myext');
      fs.writeFile(filePath, data.content, 'utf8', (err) => {
        if (err) {
          return res.status(500).send('Error saving .myext file');
        }
        res.send('File saved successfully');
      });
    });
  });


app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Enter fullscreen mode Exit fullscreen mode

lang.js

function myCustomFunction() {
    console.log('Custom function executed!');
  }

  myCustomFunction(); // Call the function

Enter fullscreen mode Exit fullscreen mode

example.myext

myCustomFunction();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)