0

I'm trying to do loop to write files, I need to know how to load a file as cities.txt, this content inside looks like:

Los Angeles
San Francisco
St. Louis
New York
Philadelphia
Miami
Houston
Dallas
Kansas City
Memphis
...

This list includes new line, I'm looking a script to do loop, the output would be like this screenshot:

loop list

Also the space string needs to be replaced from " " to "-" to prevent error due to naming file rules.

Ivan
  • 1,221
  • 2
  • 21
  • 43
  • You want to know how to load a series of txt files in Node.js and do something with their respective content. Did I get that right? – James Hibbard Dec 28 '15 at 17:45
  • @JackZelig Yes but just one txt file which contains list of cities, that's all – Ivan Dec 28 '15 at 17:47

1 Answers1

1

You can do it with readline, the core node module.

var fs = require('fs');

var lr = require('readline').createInterface({
  input: require('fs').createReadStream('cities.txt')
});

lr.on('line', function (line) {
  var fileName = line.replace(" ", "-").toLowerCase();
  fs.writeFileSync(fileName + ".json", '');
});

This SO thread is quite helpful: Read a file one line at a time in node.js?

Community
  • 1
  • 1
James Hibbard
  • 16,490
  • 14
  • 62
  • 74