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.

2
  • 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? Commented Dec 28, 2015 at 17:45
  • @JackZelig Yes but just one txt file which contains list of cities, that's all Commented Dec 28, 2015 at 17:47

1 Answer 1

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?

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

1 Comment

It didn't write the files, it only shows list of cities in console.

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.