0

Would like to write data into specific folder using writefile in node js.

I have seen couple of questions in stackoverflow regarding this but none of them worked for me .

For example :

fs.writeFile('./niktoResults/result.txt', 'This is my text', function (err) {
    if (err) throw err;
    console.log('Results Received');
});

This throws an error "NO SUCH FILE OR DIRECTORY"

Is there any alternative for writing data into specific folder node js ???

Jakka rohith
  • 295
  • 1
  • 3
  • 11
  • First, I'd suggest using `__dirname` and not `./` prefix. Secondly, maybe the directory `niktoResults` doesn't exist. Check this thread for how to verify directory existence https://stackoverflow.com/questions/21194934/node-how-to-create-a-directory-if-doesnt-exist – Aviad Oct 04 '19 at 10:41
  • So there is node won't create folder if the folder doesn't exist – Jakka rohith Oct 04 '19 at 10:45

2 Answers2

3

Ensure that the directory is available & accessible in the working directory. In this case, a function like below needs to be called at the start of the application.

function initialize() {
  const exists = fs.existsSync('./niktoResults');
  if(exists === true) {
    return;
  }
  fs.mkdirSync('./niktoResults')
}
explorer
  • 868
  • 7
  • 17
0

Error caused by directory not existing, create a directory if it does not exist.

function create(text, directory, filename)
{
    if (!fs.existsSync(directory)) {
        fs.mkdirSync(directory);
        console.log('Directory created');
        create(text, directory);
    } else {
        fs.writeFile(`${directory}/${filename}`, `${text}`, function (error) {
            if (error) {
                throw error;
            } else {
                console.log('File created');
            }
        });
    }

}

create('Text', 'directory', 'filename.txt');
ABC
  • 1,805
  • 1
  • 7
  • 17