简体   繁体   English

打印文件中的换行数(node.js)

[英]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).它应该记录“12”时记录“0”(在我的测试 README.md 中)。 Changing "/n" to "\\n" fixed this and the following code worked just fine将“/n”更改为“\\n”修复了这个问题,下面的代码工作得很好

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. "\\n" 是换行符的正确转义序列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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