Question

I'm trying to split text into an array and then ultimately create a new file with the contents of that array.

However, when I do this, the text file contains a comma-delimited list instead of using array notation.

Here is the code so far:

var input = "4 Every Dog Must Have His 66 Every Day,";

var lorem = function(text) {
  var textArray = input.split(' ');

  for (var i = textArray.length - 1; i >= 0; i--) {
    if (textArray[i].match(/(\d+)$/)) {
      textArray.splice(i, 1);
    }
  }

  return textArray;

};

output = lorem(input);

var fs = require('fs');
fs.writeFile("test", output, function(err) {
    if(err) {
        console.log(err);
    } else {
        console.log("The file was saved!");
    }
}); 
Was it helpful?

Solution

writeFile expects data to be a String or a Buffer, so it is printing the .toString() representation of your array. This looks something like "Every,Dog,Must"....

Wrap it with JSON.stringify(output) to get a nice JSON representation "['Every','Dog','Must',....]".

OTHER TIPS

What do you mean by array notation? Isn't that a comma delimited string with brackets? Try this.

output = "[" + output.join(', ') + "]";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top