Junior — Middle
Can you list and describe the main synchronous functions available in Node.js environment?
sobes.tech AI
Answer from AI
In Node.js, there are several core synchronous functions commonly used for working with the file system and other tasks. Here are some of them:
fs.readFileSync(path[, options])— reads the contents of a file synchronously.fs.writeFileSync(path, data[, options])— writes data to a file synchronously.fs.existsSync(path)— checks if a file or directory exists.fs.mkdirSync(path[, options])— creates a directory synchronously.fs.readdirSync(path[, options])— reads the contents of a directory synchronously.fs.statSync(path)— retrieves information about a file or directory synchronously.
Example of using readFileSync:
const fs = require('fs');
try {
const data = fs.readFileSync('example.txt', 'utf8');
console.log(data);
} catch (err) {
console.error('File read error:', err);
}
Synchronous functions block the execution thread, so they should be used with caution, especially in server applications, to avoid degrading performance.