NodeJS Program to Create File If Missing with Explanation
NodeJS
Easy
File System & Paths
37 views
1 min read
86 words
This problem helps you practice core NodeJS fundamentals in a practical way. It builds intuition around file, create, exist. Let’s break it down step by step so you can implement it confidently.
Problem Statement
If file does not exist, create it with 'meetcode' and print CREATED/EXISTS.
Input Format
stdin: file path.
Output Format
Print one word.
Constraints
Use fs.existsSync.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
const fs = require('fs');
const p = fs.readFileSync(0, 'utf8').trim();
if (!p) process.exit(0);
if (fs.existsSync(p)) {
console.log('EXISTS');
} else {
fs.writeFileSync(p, 'meetcode', 'utf8');
console.log('CREATED');
}
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
If file does not exist, create it with 'meetcode' and print CREATED/EXISTS.
Input / Output
Constraints
Use fs.existsSync.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
const fs = require('fs');
const p = fs.readFileSync(0, 'utf8').trim();
if (!p) process.exit(0);
if (fs.existsSync(p)) {
console.log('EXISTS');
} else {
fs.writeFileSync(p, 'meetcode', 'utf8');
console.log('CREATED');
}
Solutions (0)
No solutions submitted yet. Be the first!