For any file operations, you will need the filesystem module:
const fs = require('fs');
Reading a String
fs.readFileSync
behaves similarly to fs.readFile
, but does not take a callback as it completes synchronously and therefore blocks the main thread. Most node.js developers prefer the asynchronous variants which will cause virtually no delay in the program execution.
If an encoding option is specified, a string will be returned, otherwise a Buffer will be returned.
// Read a string from another file synchronously
let content;
try {
content = fs.readFileSync('sync.txt', { encoding: 'utf8' });
} catch(err) {
// An error occurred
console.error(err);
}
With all that being said, I highly recommend you keep learning!
Thank you for reading this article. Please feel free to connect with me on LinkedIn and Twitter.
Node.js : Determining the line count of a text file
Rajesh Kumar Yadav ・ May 20 '21
#node
#programming
#webdev
#javascript
Node.js : Reading a file line by line
Rajesh Kumar Yadav ・ May 19 '21
#node
#programming
#webdev
#javascript
Node.js : Reading from a file synchronously
Rajesh Kumar Yadav ・ May 12 '21
#node
#programming
#webdev
#javascript