Question: I want to split a file: each line in a separate file. The initial file is really big. I finished with code bellow:

```
var fileCounter = -1;

function getWritable() {
      fileCounter++;
      writable = fs.createWriteStream('data/part'+ fileCounter + '.txt', {flags:'w'});
      return writable;
}

var readable = fs.createReadStream(file).pipe(split());
readable.on('data', function (line) {
    var flag = getWritable().write(line, function() {
      readable.resume();
    });
    if (!flag) {
      readable.pause();
    }
});

```

It works but it is ugly. Is there more nodish way to do that? maybe with piping and without pause/resume.

*NB: it's not a question about lines/files/etc . The question is about streams and I just try to illustrate it with the problem*

Answer: 
You can use [Node's built-in `readline` module](https://nodejs.org/api/readline.html).

```
var fs = require('fs');
var readline = require('readline');
var fileCounter = -1;

var file = "foo.txt";
readline.createInterface({
    input: fs.createReadStream(file),
    terminal: false
}).on('line', function(line) {
   var writable = fs.createWriteStream('data/part'+ fileCounter + '.txt', {flags:'w'});
   writable.write(line);
   fileCounter++
});

```

Note that this will lose the last line of the file if there is no newline at the end, so make sure your last line of data is followed by a newline.

Also note that the docs indicate that it is Stability index 2, meaning:

> 
> Stability: 2 - Unstable The API is in the process of settling, but has
>  not yet had sufficient real-world testing to be considered stable.
>  Backwards-compatibility will be maintained if reasonable.
> 
> 
>
How about the following? Did you try? Pause and resume logic isn't realy needed here.

```
var split = require('split');
var fs = require('fs');
var fileCounter = -1;

var readable = fs.createReadStream(file).pipe(split());
readable.on('data', function (line) {
    fileCounter++;
    var writable = fs.createWriteStream('data/part'+ fileCounter + '.txt', {flags:'w'});
    writable.write(line);
    writable.close();
});

```

Piping dynamically would be hard...

---

EDIT: You could create a [writable](https://nodejs.org/api/stream.html#stream_class_stream_writable) (so `pipe()`able) object that would, `on('data')` event, do the "create file, open it, write the data, close it" but it :

* wouldn't be reusable
* wouldn't follow the KISS principle
* would require a special and specific logic for file naming (It would accept a string pattern as an argument in its constructor with a placeholder for the number. Etc...)

I realy don't recommend that path, or you're going to take ages implementing a non-realy-reusable module. Though, that would make a good *writable* implementation exercise.