Node.js Error: ENOENT: no such file or directory (2024) | TechGeekNext

Node.js Error: ENOENT: no such file or directory (2024)

In this tutorial, we will help you to resolve the Error: ENOENT: no such file or directory, open 'student.json' issue.

Q: What is fs module in Nodejs?
Ans:

Node.js provides an inbuilt component called FS (File System). The Node. js file system module enables us to interact with our computer's file system.

Error: ENOENT: no such file or directory

Error: ENOENT: no such file or directory, open 'student.json'
    at Object.openSync (node:fs:585:3)
    at Object.readFileSync (node:fs:453:35)
    at Object.writeStudentData (D:\nodejs\file-example\student-service-impl.js:24:21)
    at Object.handler (D:\nodejs\file-example\student-app.js:10:17)
    at D:\nodejs\file-example\node_modules\yargs\build\index.cjs:1:8891
    at j (D:\nodejs\file-example\node_modules\yargs\build\index.cjs:1:4956)
    at M.handleValidationAndGetResult (D:\nodejs\file-example\node_modules\yargs\build\index.cjs:1:8860)
    at M.applyMiddlewareAndGetResult (D:\nodejs\file-example\node_modules\yargs\build\index.cjs:1:9502)
    at M.runCommand (D:\nodejs\file-example\node_modules\yargs\build\index.cjs:1:7231)
    at Xt.[runYargsParserAndExecuteCommands] (D:\nodejs\file-example\node_modules\yargs\build\index.cjs:1:57762) {
  errno: -4058,
  syscall: 'open',
  code: 'ENOENT',
Follow below steps to resolve Error: ENOENT: no such file or directory, open 'student.json' issue.
  1. This problem occurs when a file does not exist; therefore, check to see if the file exists first.
  2. The suitable approach is to use fs.openSync, it returns the file descriptor.
  3. If the file does not exist, the w flag ensures that it is created, and if it does, it is overwritten with a new file, overriding its content.
  4. If users don't need the file descriptor, users can close the file by wrapping the call in a fs.closeSync() call.
//check if file exist
if (!fs.existsSync('student.json')) {
    //create new file if not exist
    fs.closeSync(fs.openSync('student.json', 'w'));
}

Recommendation for Top Popular Post :