DEV Community

Rajesh Kumar Yadav
Rajesh Kumar Yadav Subscriber

Posted on • Edited on

2 1

Node.js : Reading from a file synchronously

For any file operations, you will need the filesystem module:



const fs = require('fs');


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

Buy Me A Coffee

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.

Top comments (0)

11 Tips That Make You a Better Typescript Programmer

typescript

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay