1

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!");
    }
}); 

2 Answers 2

3

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',....]".

Sign up to request clarification or add additional context in comments.

Comments

2

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

output = "[" + output.join(', ') + "]";

1 Comment

This totally works, but I think the most correct answer is using JSON.stringify(output).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.