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'
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.
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.
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.
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');
})
}
})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With