2

I have a array, its contents is, lines written like so.

John
Snow
foo 
1234 

Is it possible to put each line into its own variable? The max line count will be 7 lines.

I use this code to read the file into an array.

    var fs = require('fs');
    var array = fs.readFileSync('foo').toString().split("\n");
    for(i in array) {
    console.log(array[i]);

I was thinking of using the Split and Map function, but that would only result in,

John, Snow, foo ,1234 Which is not what I'm after.

My reasoning.

I am working on a little software sharing app,what I was planning, is if one of the packages needs installing, I was going to have a simple system that would allow the installation of the package like so,

unpack 
install 
etc 

Using internal functions in the app to simplify installation, so the developers don't need to write out large install scripts, I wanted to read line by line in the file, split each line into its own variable or array, then check the value of each array, then start the correct functions.

feprh
  • 21
  • 2
  • 1
    Could you give an example input/output of what you're trying to do? – user1582024 Jul 24 '16 at 18:48
  • 1
    Why you need each result in its own variable? Why it doesn't work for you with an array? – dlopez Jul 24 '16 at 18:49
  • 1
    Are you looking for destructuring assignment? `[v0,v1,v2,v3,v4,v5,v6] = array;` – Arnauld Jul 24 '16 at 18:50
  • Would that be the same as, array[0] and array[1]? – feprh Jul 24 '16 at 18:53
  • How would I achieve that? – feprh Jul 24 '16 at 18:55
  • The solution that @Arnauld suggested to you only works with Javascript 6, afaik. – dlopez Jul 24 '16 at 19:12
  • How does one do a restructuring assignment? I believe, JS 6 can be executed in node6? – feprh Jul 25 '16 at 12:07
  • @feprh A destructuring assignment on a array would work exactly as I wrote it: `[a,b] = someArray;`. I think it should be available in the most recent versions of Node. According to [this post](http://stackoverflow.com/questions/17379277/destructuring-in-node-js), you may have to run Node with the `--harmony_destructuring` flag, though. – Arnauld Jul 25 '16 at 14:18

1 Answers1

0

You can use the join() method

var str = array.join(",");
console.log(str); // John,Snow,foo,1234
kevin ternet
  • 4,514
  • 2
  • 19
  • 27