Software Development Engineer

Blog PostsResume

Editing a file stored in the webserver from the WebApp

As a developer, working on a web application, you may want your users to be able to edit a file stored in your webserver. There may be certain use cases in which this may be required. Consider, for instance, you want your user to edit a file in their Github repository, perform certain actions and then Publish the changes.

I have prepared a script using ExpressJS and Socket.IO which can perform the following action. At the client side, we define a retrieve-file event which emits a request to the server. At the server side, we handle the event by executing a retrieveContent(...) function which uses spawn method of child_process to execute a script that retrieves the content of a file.

// Client Side
$(function () {
  var socket = io();
  ....
  ....
  $(“#editor-button”).click(function () {
    socket.emit(“retrieve-file”);
  });
  ....
  ....
});

// Server Side
io.on(“connection”, function (socket) {
  socket.on(“retrieve-file”, function () {
    retrieveContent(socket);
  });
  ....
  ....
});

var retrieveContent = function (socket) {
  var process = require(“child_process”).spawn(“cat”, [“.travis.yml”]);
  process.stdout.on(“data”, function (data) {
    socket.emit(“file-content”, data);
  });
};

After the file content is retrieved from the server, we use a Javascript Editor like ACE to edit the content of the file. Making all the changes to the file, we emit a store-content event. At the server side, we handle the event by executing a storeContent(...) function which uses exec method of child_process to execute a bash script that stores the content to the same file.

$(function () {
  var socket = io();
  var editor = ace.edit(“editor”);
  ....
  ....
  socket.on(“file-content”, function (data) {
    editor.setValue(data, -1);
  });
  ....
  ....
  $(“#save-modal”).click(function () {
    socket.emit(“store-content”, editor.getValue());
  });
});

io.on(“connection”, function (socket) {
  ....
  socket.on(“store-content”, function (data) {
    storeContent(socket, data);
  });
});

var storeContent = function (socket, data) {
  var script = ‘truncate -s 0 .travis.yml && echo “’ + data + ‘“ >> .travis.yml’;
  var process = require(“child_process”).exec(script);
  
  process.on(“exit”, function (code) {
    if (code === 0) {
      socket.emit(“save-successful”);
    }
  });
};

After successful execution of the script, a successful event is sent to the client-side which can then be handled.

A minimal sample of this application can be found at: https://github.com/imujjwal96/socket-editor


© 2024 Ujjwal Bhardwaj. All Rights Reserved.