Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the data not written to the file?

I have this code which is supposed to write data in text file:

const test = [
  'test1',
  'test2'
]
fs.writeFile('file.txt', test, {flag: "a"}, err => {
  if (err) throw err
})

The problem is that code works without errors, but there is no data in file. If I just put and execute this piece of code in some test file, it works correctly, but not in function, where this code is supposed to be. What’s wrong? Why there is no data in file if I execute code in function, but everything works correctly, when I execute it in test file?

Here is the code of function:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const fs = require("fs");

(async () => {
    const test = [
      'test1',
      'test2'
    ]
    fs.writeFile('file.txt', test, {flag: "a"}, err => {
      if (err) throw err
    })

    process.exit(1);
  } catch (e) {
    console.log('error: ', e)
    process.exit(1)
  }
})()

>Solution :

You’re missing the "try" part of your try/catch.

You’re also exiting the script before the file is written.

try writeFileSync instead.

const fs = require("fs");

(async() => {
  const test = [
    'test1',
    'test2'
  ]
  try {
    fs.writeFileSync('file.txt', test, {
      flag: "a"
    });
    process.exit(1);
  } catch (e) {
    console.log('error: ', e)
    process.exit(1)
  }
})()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading