Open michaelgrilo opened 9 years ago
michaelgrilo,
You need to use the toString() method because readFileSync returns a buffer and you need to turn it into a string in order to find the newline characters (see https://nodejs.org/api/fs.html#fs_fs_readfilesync_filename_options for more on readFileSync). My solution was a lot more broken down than the official one. I'm not sure where they were asking us to recall .split() from, but I knew it from other orgramming. As for the -1, it says at the end of the instructions that the test file does not have a newline character ('\n') at the end of the last line, so you'll end up with an array that has one more element than the number of newlines. This means you'll have to subtract one.
My solution was a lot longer than the official one. Maybe seeing it will help you break things down. // gets fs module var fs = require('fs');
// gets the full path var filename = process.argv[2];
// returns a buffer object var file = fs.readFileSync(filename);
// converts it to a string var str = file.toString();
// Number of newlines var res = str.split('\n'); var newLines = res.length - 1;
console.log(newLines);
@KelCard this all makes perfect sense but im testing a file with 245 lines and when i run my script i get 21. is "\n" counted differently?
Having come from the
javascripting
module, and completed the first two exercises in this module, I was not able to find a solution to this problem.The first assumption that the instructions make is that I would know how and where to use the
toString()
method.It is also stated for me to "recall"
.split()
, but I haven't used this before. Additionally, it's not clear what a delimiter is. I can guess, but it's an assumption that we might not want to make in beginner tutorials.Looking at the solution, I also don't understand what the
- 1
at the end of line 4 does. How would I have known to include that?