Anna
Anna

Reputation: 571

writeFileSync doesn't callback

I am using writeFileSync function to write a file locally, the file does get written, however, the callback function is never called.

I did some googling, some other post are having the issue that it's either 1) passing the content went wrong or 2) having two write function at the same time.

My problem is that there are some other places in my code that is using the writeFileSync, but they are on different routes (not sure if this is the right terminology, localhost:port#/differentroutes <- something like this). I am testing only on my own route so those write functions shouldn't even be called.

Here is my code:

if(!fs.existsSync(dir)){
        fs.mkdirSync(dir)
    }

//content is just a string var I swear it's just a string

    fs.writeFileSync('./pages/SubmissionProcess.html',content,function(err){
        if(err){
            throw err
        }else {
            console.log("YES")
        }
    })

I never see this "YES" nor error in my console even tho the file is already written....

Upvotes: 0

Views: 4761

Answers (2)

Jake Holzinger
Jake Holzinger

Reputation: 6063

All of the synchronous methods throw rather than passing an error to a callback.

try {
    fs.writeFileSync('./pages/SubmissionProcess.html', content);
    console.log('YES');
} catch (e) {
    console.error(e);
}

Upvotes: 2

Eddie D
Eddie D

Reputation: 1120

Write file sync doesn't take a callback :D

Take a look at the documentation :

https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options

The parameters are (path, data, options)

If you want to check if the file actually wrote, you can read file sync after writing it or check the last time the file was updated. Otherwise, you should try using the async approach.

Upvotes: 3

Related Questions