path module?import path from 'path'; console.log(path.join('folder', 'subfolder', 'file.txt'));
path.join method works on Windows systems.The path.join method joins path segments using the platform-specific separator. On Windows, it uses backslashes \\, so the output is folder\\subfolder\\file.txt. On POSIX systems, it uses forward slashes.
fs module's readFileSync method on a non-existent file?import fs from 'fs'; try { const data = fs.readFileSync('nofile.txt', 'utf8'); console.log(data); } catch (err) { console.log('Error caught'); }
readFileSync behaves when the file is missing and how the try-catch block works.The readFileSync method throws an error if the file does not exist. The try-catch block catches this error and prints 'Error caught'.
os module in a Node.js ES module environment?require is not used in ES modules and how to import entire modules.In ES modules, to import the entire os module, use import * as os from 'os';. Option A uses CommonJS syntax which is not valid in ES modules. Option A tries to destructure a non-exported member.
import http from 'http'; const server = http.createServer((req, res) => { res.write('Hello World'); res.end(); }); server.listen(3000); console.log('Server running on port 3000'); // Later in code server.listen(3000);
Calling server.listen(3000) twice causes an error because the port is already in use by the first call. This results in an EADDRINUSE error.
events module. What will be the output when the event is emitted?import EventEmitter from 'events'; const emitter = new EventEmitter(); emitter.on('ping', () => console.log('First listener')); emitter.once('ping', () => console.log('Second listener')); emitter.emit('ping'); emitter.emit('ping');
on and once listeners.The on listener runs every time the event is emitted. The once listener runs only the first time. So the first emit triggers both listeners, printing 'First listener' and 'Second listener'. The second emit triggers only the on listener, printing 'First listener' again.