Prince Andrews
Prince Andrews

Reputation: 3

Print number of newlines from a file (node.js)

This code gives compile time error, can anyone help please ?

const fs = require('fs')

var str_contents  = fs.readFileSync('./README.md', 'utf8');

var numOflines = str_contents.split('/n').length - 1;

console.log(numOflines);

Upvotes: 0

Views: 196

Answers (1)

JoshuaK98
JoshuaK98

Reputation: 381

I ran your code and I didn't get a compile time error. It logged "0" when it should've logged "12" (in my test README.md). Changing "/n" to "\n" fixed this and the following code worked just fine

const fs = require('fs')
var str_contents  = fs.readFileSync('./README.md', 'utf8');
var numOflines = str_contents.split('\n').length - 1;
console.log(numOflines);

"\n" is the proper escape sequence for a newline.

Upvotes: 1

Related Questions