Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
like image 452
Danyal Ahmad Avatar asked Jan 23 '19 06:01

Danyal Ahmad


People also ask

How do I create a node js file in a specific directory?

Example 1 – Create File using writeFile() txt . // include node fs module var fs = require('fs'); // writeFile function with filename, content and callback function fs. writeFile('newfile. txt', 'Learn Node FS module', function (err) { if (err) throw err; console.

How do I save a file to a specific directory in JavaScript?

you can also use window. showDirectoryPicker() to ask for a specific folder and ask for write permission to that folder... then you can write data to wherever you want without prompting the user further. this new picker should have an option for hinting where it should save a file.

How do you write data to a file in node JS?

The fs. writeFile() method is used to asynchronously write the specified data to a file. By default, the file would be replaced if it exists. The 'options' parameter can be used to modify the functionality of the method.


2 Answers

Do this

const fs = require('fs');
const path = require('path');

let baseDir = path.join(__dirname, '/./niktoResults/');
fs.open(`${baseDir}+result.txt`, 'wx', (err, desc) => {
  if(!err && desc) {
     fs.writeFile(desc, 'sample data', (err) => {
       // Rest of your code
       if (err) throw err;               
       console.log('Results Received');
     })
  }
})
like image 200
elraphty Avatar answered Oct 07 '22 13:10

elraphty


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.

like image 21
Lucifer Avatar answered Oct 07 '22 12:10

Lucifer