0

(I'm a new user, so sorry if this is a bit confusing)

Basically, I would like to use a command to save the value of an array (myArray) to a separate file (myArray.txt), and then use another command to replace the value of the array (myArray) with the value of the file (myArray.txt).

So, command A puts the value of myArray into myArray.txt

While command B clears the value of myArray, and puts the value of myArray.txt into myArray.

Once again, I'm new, so sorry if this is a little hard to understand, or if I did something wrong.

  • Please note that these are asynchronous IO operations. Take a look at these two SO questions [**read**](http://stackoverflow.com/questions/22863170/node-js-from-fs-readfilesync-to-fs-readfile) and [**write**](http://stackoverflow.com/questions/2496710/writing-files-in-node-js). For the format, I'd recommend [**JSON**](http://stackoverflow.com/questions/5726729/how-to-parse-json-using-node-js) – Paul S. Jul 10 '16 at 00:00
  • @PaulS. Thatnks for the fast reply, I'll take a look. – ThatCoder Jul 10 '16 at 00:01

1 Answers1

0

Apart from a astonished "why?!", you can save an array in a JSON encoded form to file like so:

const fs = require('fs');
const path = 'path/to/myArray.txt';

fs.writeFile(path, JSON.stringify(myArray), err => {
  if (err) // start cyring;    
});

To retrieve the file, you use fs.readFile, or you can simply require the file it only contains JSON.

1sloc
  • 1,180
  • 6
  • 12
  • This works, but when using fs.readFile, how would I set myArray equal to the value it read? (Sorry if that sounds confusing) – ThatCoder Jul 10 '16 at 00:05
  • Inside the callback of `fs.writeFile`, you have access to the file data. There you could say: `myArray = JSON.parse(data)`. Or, as said before, if the file is pure json, you don't need `fs` and can simply do `myArray = require(path)`. – 1sloc Jul 10 '16 at 00:08
  • Thanks, I'll try that out. – ThatCoder Jul 10 '16 at 00:08
  • So, writing the array to a file works perfectly, however I'm still unable to write the file to an array. I've tried both myArray = JSON.parse(data) and myArray = require(path) and neither seem to work. – ThatCoder Jul 10 '16 at 00:26
  • It should. How do you access data in your first example? It should be like this: https://fiddle.jshell.net/u82kp5o5/ – 1sloc Jul 10 '16 at 00:32