1 year ago

#373890

test-img

Brianna

NodeJS fs.writeFile simply will not write the file to the correct directory

I have been working on trying to fix this for two hours. I am using macOS. I have copied my professor's code to the T. The path is correct. fs.writeFile just... won't write the file into the correct directory.

const fsPromises = require('fs').promises;
const path = require('path');
const fileOps = async () => {
try {
    const data = await fsPromises.readFile(path.join(__dirname,'files','starter.txt'), 'utf8'); //don't need the error catch
    console.log(data);
    await fsPromises.writeFile(path.join(__dirname,'files','promiseWrite.txt'), data);
    await fsPromises.appendFile(path.join(__dirname,'files','promiseWrite.txt'), '\n\nNice to meet you.');
    await fsPromises.rename(path.join(__dirname,'files','promiseWrite.txt'), 'promiseComplete.txt');
    const newData = await fsPromises.readFile(path.join(__dirname,'files','promiseComplete.txt'), 'utf8'); 
    console.log(newData);
} catch (err) {
    console.error(err);
}
}
fileOps();

The code will create the promiseWrite.txt file, but not in the files folder. Instead it's next to my index.js file in my parent folder. The code will also successfully append the text to the file that's been created in the wrong place, and will rename the file as well. But then, when I try to log newData to the console, the file is, of course, not found. I have tried using a direct path to the files folder with the same results. Please, I'm going crazy, has anyone had a similar experience? Does anyone have any advice?

EDIT:

I'm still hoping for any advice as to why the above doesn't work, but I found that this works:

fsPromises.writeFile(path.join(__dirname,'files','reply.txt'), 'Nice to meet you', (err) => {
if (err) throw err;
console.log('Write Complete'); })

I'm not sure why this works but the above doesn't.

javascript

node.js

macos

fs

0 Answers

Your Answer

Accepted video resources