Search code examples
javascriptnode.jsfs

How to write a file to specific directory in NodeJS?


I am writing some text to a file us the fs module.

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

Now this works fine. I want to write this file to a niktoResults folder in my project but when i do

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

It results an error. I don't know how to define the directory path that will help me overcome this.

Error:
Error: ENOENT: no such file or directory, open '/niktoResults/[object Object].txt'

Solution

  • You have to understand that you can give either absolute path or relative path. Currently what you can do is

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

    Here . refers to current directory. Therefore ./niktoResults refers to niktoResults folder in current directory.