最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to print each element of an array in new line in txt file using javascript? - Stack Overflow

programmeradmin2浏览0评论

My result set is an array that returns from a function.

['item1','item2','item3','item4','item5','item6','item7','item8']

I am writing it into a file using

fs.writeFile('out.txt', uniqueMatches, (err)=>{
     if(err) throw err;
          console.log('Extract saved successful');
});

I see the out.txt as

item1, item2, item3, item4, item5, item6, item7,item8

How do I print them as?

item1
item2
item3
item4
item5
item6
item7
item8

My result set is an array that returns from a function.

['item1','item2','item3','item4','item5','item6','item7','item8']

I am writing it into a file using

fs.writeFile('out.txt', uniqueMatches, (err)=>{
     if(err) throw err;
          console.log('Extract saved successful');
});

I see the out.txt as

item1, item2, item3, item4, item5, item6, item7,item8

How do I print them as?

item1
item2
item3
item4
item5
item6
item7
item8
Share Improve this question edited Sep 5, 2018 at 17:45 Heretic Monkey 12.1k7 gold badges61 silver badges131 bronze badges asked Sep 5, 2018 at 17:27 Azim ShaikAzim Shaik 1913 gold badges5 silver badges15 bronze badges 4
  • is uniqueMatches your array? – petey Commented Sep 5, 2018 at 17:29
  • 1 Maybe uniqueMatches.join("\n") – epascarello Commented Sep 5, 2018 at 17:29
  • 1 Check out Array.join. Just join the items with \n, and you should be good. – mccambridge Commented Sep 5, 2018 at 17:29
  • have you tried to iterate your uniqueMatches array construct a string where you append "\r\n" to the end of each item? – Pedro Simão Commented Sep 5, 2018 at 17:30
Add a ment  | 

2 Answers 2

Reset to default 3

Try to use the join() to add the new lines :

fs.writeFile('out.txt',
    uniqueMatches.join('\n'),
    function (err) { console.log('Extract saved successful'); }
);

Use .join to add a line break to your data array that is to be written:

fs.writeFile('out.txt', uniqueMatches.join('\n');, (err)=>{
            if(err) throw err;
            console.log('Extract saved successful');
        });
发布评论

评论列表(0)

  1. 暂无评论