简体   繁体   中英

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM