Node.js Tutorial – 4 Reading File in node.js


Previous tutorials on node.js could be found at [1], [2], [3].

Reading files is easy in node.js via the package fs. The following shows the straightforward procedure in event-driven model to read a text file that contains simply ‘Hello, World!’ string.

nodejs-file-1 Node.js Tutorial - 4 Reading File in node.js beginner I/O File implementation internet javascript network nodejs programming languages

The file are not read in immediately, instead, it tells node.js that when the file checks completes (stat) and do a further check if it is a file (not a directory) and then start reading file contents using fs.readFile however this is a non-block I/O, it continues execution. When the file reading is completed, it notifies with either data on success or err on errors.

If the file size is huge, we can try an alternative which is more efficient via using the stream, we specify the event on(‘data’).

nodejs-file-2 Node.js Tutorial - 4 Reading File in node.js beginner I/O File implementation internet javascript network nodejs programming languages

Both examples are easy to understand the following is the outcome.

nodejs-file-3 Node.js Tutorial - 4 Reading File in node.js beginner I/O File implementation internet javascript network nodejs programming languages

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
340 words
Last Post: Node.js Tutorial - 3 Creating a Chat Server using TCP Sockets
Next Post: Make Sure Run Script under 32-bit cscript.exe or wscript.exe when 32-bit COM object is required.

The Permanent URL is: Node.js Tutorial – 4 Reading File in node.js

Leave a Reply