1

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 ???

2
  • 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 stackoverflow.com/questions/21194934/…
    – Aviad
    Oct 4, 2019 at 10:41
  • So there is node won't create folder if the folder doesn't exist Oct 4, 2019 at 10:45

2 Answers 2

5

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')
}
1

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');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.