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/… Commented Oct 4, 2019 at 10:41
  • So there is node won't create folder if the folder doesn't exist Commented 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')
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.