Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

237
Views
how can i throw an error if exist and stop writing with node fs?

I have found an error writing a wrong variable, when writing the file, due to that error, the file has been written wrong, deleting everything that was in it, leaving it blank.

fs.writeFile(
  path.join(__dirname,"../example/path/file.json") , 
  JSON.stringify(var)
);

How can i make: "If error exist, dont try to write the file and throw an error via console"

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You read the documentation and open/write to the file with the correct flags:

const fs = require('fs/promises');

async function writeFile(fn, content) {
    const opts  = {

        // assuming that content is a string
        encoding: 'utf8',

        // 'wx' opens a file for writing.
        // The file is created if it does not exist,
        // and rejects if the file does exist.
        flag: 'wx', 

    };

    // returns undefined on success, or an error
    return await fs
                 .writeFile(fn, content, opts)
                 .catch( err => err )
                 ;
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!