6

Here is the command that is broken:

fs.writeFileSync('Metadata.json', metadataString);
console.log("Metadata written.");

I have placed a breakpoint and verified that metadataString is actually a string. The console logs Metadata written just fine and the file stays empty...

Not sure what else I can check... Thanks in advance.

1
  • Delete Metadata.json and see if fs.writeFileSync() is creating the file or not. Commented Oct 23, 2015 at 0:12

3 Answers 3

2

fs.writeFileSync() throws an Error exception if it fails. Use a try/catch block:

try {
    fs.writeFileSync('Metadata.json', metadataString);
} catch (err) {
    console.log('Error writing Metadata.json:' + err.message)
}
Sign up to request clarification or add additional context in comments.

2 Comments

Wouldn't this be seen on stdout anyway if his code fails?
My code have a try catch, it's not failing but it's not recording my files too.
0

I have the same problem, fs.writeFile instead of fs.writeFileSync and it worked. In your solution, it might be:

fs.writeFileSync('Metadata.json', metadataString, (err) => {
   if (err) console.log(err);
});

Comments

0

You can use writeFileSync for the same and pass your string and add encoding:'utf8' though it is default. And For Error Handling you can always put try catch block. Also put an await till your string data is loaded.(In case If you are using a larger data set)

try {
    let yourString = `{"HI":"This is Test Creating A File"}`;
    fs.writeFileSync(fileName, await yourString, { encoding: 'utf8' });
} catch (error) {
    console.log('File Creation Error',error);    
}

PS: Don't forget to import fs from 'fs';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.