Home > Net >  writeFile don't find directory
writeFile don't find directory

Time:11-08

I am practicing a simple application that reads and writes to a file. I'm using writeFile from "fs/promises"

When I import the file with the correct string I get the desired file

const content: Employe_T_nodel[] = require('../databace/employees.json')

But when I try to write to the file, I get an error: no such file or directory, open 'D: ...

This is the code I use. Note that I use the exact same string

async function saveAllEmployeesAsync(employeesArr: Employe_T_nodel[]) {
    const content: string = JSON.stringify(employeesArr)
    await writeFile('../databace/employees.json', content)
    return console.log("Employees saved sucsessfuly")
}

I don't understand why one function gets the path string and one doesn't

CodePudding user response:

This is because require() treats paths as relative to the current file, while fs.writeFile treats paths as relative to the path from which the Node.js process was started from.

If you want the same behavior you can use path.resolve():

async function saveAllEmployeesAsync(employeesArr: Employe_T_nodel[]) {
    const content: string = JSON.stringify(employeesArr)
    await writeFile(path.resolve(__dirname, '../databace/employees.json'), content)
    return console.log("Employees saved sucsessfuly")
}

CodePudding user response:

fs.writeFile(dir, data, err => {
  if (err) {
    console.log("File not saved!   ", err);
    return err;
  } else {
    console.log("File saved!");
    return 200;
  }
});
  • Related