简体   繁体   中英

Node.js: How to read the last non-empty line only of a txt file?

Let's say I have a text file called example.exe that is like this:

Line 1 Stuff
Line 2 Stuff
(more lines here)
Line N (Last Line) Stuff
(empty line \n)

I want to be able to read the last line of the file only, so in this case "Line N (Last Line) Stuff" and store it inside a string. Also, I do know you can read line-by-line, but I want to reduce runtime and not have out of memory errors occur as the text file gets bigger. Anybody want to help me with this? I would prefer no this done using require('fs').

Assuming you store the content in a variable content you can split the content by lines...

var lines = content.split("\n")

...and check if the last line is empty...

var lastLine = lines[lines.length-1].length ? lines[lines.length-1] : lines[lines.length-2]

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