-1

Suppose I have a file on server file1.js

Now my file1.js contains an code:

var arr = [ {'id':1, 'name':'one'}, 
            {'id':2, 'name':'two'} ]; // array of two objects

There are two input boxes:

ID: <input id>
Name: <input name>
<button type="submit" action="xyz">

Now on clicking the submit button, I want to open file1.js and add {'id':<user_entered>, 'name':<user_entered>} i.e. an object to the existing array.

Is it doable? I don't want to involve any database here.

arr.push(..) 

is the temporary solution i.e. If I open the web page on other PC or refresh the page, the source rendered here will not contain an array of 3 objects..isn't it????

u_8398
  • 27
  • 10
  • 1
    will you can do it but not with js ^^ – ave4496 Feb 09 '17 at 19:28
  • You cannot write in server side files from javascript. Instead you can use LocalStorage object to store user data in the broser with no expiration. It's useful for you? – F.Igor Feb 09 '17 at 19:32
  • Are you trying at `file:` protocol? – guest271314 Feb 09 '17 at 19:34
  • @Igor: LocalStorage won't work in my case, what if I open the web page on other PC :| – u_8398 Feb 09 '17 at 19:38
  • @aleskv: angularjs?? – u_8398 Feb 09 '17 at 19:39
  • Possible duplicate of [Global Variable usage on page reload](http://stackoverflow.com/questions/29986657/global-variable-usage-on-page-reload) – Jared Smith Feb 09 '17 at 19:42
  • @u_8398 angular.js is still js. It even has js in the name. – Jared Smith Feb 09 '17 at 19:42
  • @JaredSmith even Node has js in it but I know it is doable using Node. Nvr mnd :) – u_8398 Feb 09 '17 at 19:48
  • @u_8398 node is *server-side*. The browser does not (for good reasons) have the ability to directly modify content on either the server or the local filesystem. – Jared Smith Feb 09 '17 at 19:51
  • @JaredSmith. this is not a dupe of what you've mentioned so you can remove that.. – u_8398 Feb 09 '17 at 20:00
  • @u_8398 yes, it is, and this question should be closed because it already has answers in the one linked: i.e. persisting data across machines / refreshes. Protip: you don't do it be rewriting JavaScript files. – Jared Smith Feb 09 '17 at 20:04
  • That is for persisting the values for refreshes not across the machines..how will my localstorage work in other system.. If you don't know the answer then don't argue..Let others contribute.. – u_8398 Feb 09 '17 at 20:09
  • Are you trying `javascript` at `file:` protocol? – guest271314 Feb 09 '17 at 20:14
  • to be very frank, I am new to this and I am not getting what this statement means :| @guest271314 – u_8398 Feb 09 '17 at 20:15
  • @u_8398 Same from perspective, here. Not certain what you are trying to achieve. Requirement at Question is not clear. _"If I open the web page on other PC"_ Is `file1.js` hosted at a server? Or, are you trying `javascript` locally? Why would changes to `file1.js` be available at "other PC"? – guest271314 Feb 09 '17 at 20:18
  • Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackoverflow.com/rooms/135465/discussion-on-question-by-u-8398-write-to-a-existing-js-file-using-javascript). – Bhargav Rao Feb 11 '17 at 19:46

1 Answers1

0

If you are in a server-side environment you could first load the file using fs.readFile, parse the JSON into a normal JS array, manipulate the array however you need (i.e. append the extra object), and then write the serialized JSON back to the same path.

It would look something like this:

fs.readFile(path.join(__dirname, 'myFile.json'), 'utf-8', (err, data) => {
      if (err) {
        console.log('Error reading file');
      }
      const myArray = JSON.parse(data);
      myArray.push({ new: 'object' });
      fs.writeFile(path.join(__dirname, 'myFile.json'), JSON.stringify(myArray), e => {
        if (e) {
          console.log('Error writing file');
        }
        console.log('Success');
      });
    });

If you are only building for the web, however, this sounds like a job for localStorage. It would work very similarly:

const savedArray = localStorage.getItem('my_saved_array');
const myArray = savedArray ? JSON.parse(savedArray) : {};
myArray.push({ new: 'object' });
localStorage.setItem('my_saved_array', JSON.stringify(myArray));

It is possible for JSON.parse to throw and error so you may want to wrap this in a try-catch. This also gets around the issue of opening the page in a different tab as localStorage is persisted for each site in the same browser. If you were to open the site in chrome and then in safari, however, localStorage will not sync.

Hope this helps.

mparis
  • 3,623
  • 1
  • 17
  • 16
  • The first solution seems to be close but as far as I can understand: you're loading the JSON file-> adding object and then putting it back. If my understanding is correct then maybe you've not understood the question. There is an array in the .js file (a normal js file that has some methods, variables and an array of two objects and to this array I need to add an object) – u_8398 Feb 09 '17 at 19:58
  • Can you move the array into its own file and then require it from the main script? Its going to be a really hard task to reliably insert text into a source file like that. – mparis Feb 09 '17 at 20:00
  • I was looking for a way to avoid DBs, server side scripting languages but I don't see a solution to it that way.. thanks :) – u_8398 Feb 09 '17 at 20:12
  • I work at [scaphold.io](https://scaphold.io) and we make it out jobs to make it easy for you to have access to a full API without any hassle. It may be worth checkin out :) – mparis Feb 09 '17 at 20:27