-
-
Notifications
You must be signed in to change notification settings - Fork 40
Description
Thank you for creating and maintaining this library. I want to report a following issue.
Currently, "data" argument is checked only for existence:
https://github.com/sindresorhus/write-json-file/blob/master/index.js#L15
If it exists, it is assumed that is it a plain object. The problem is, accidentally the data
can come as string
too and this library will silently write an empty file! For example, format-package returns a string and that's why write-json-file
in one of my libraries was silently writing empty files.
Thinking about this, we could either:
- always throw if
data
is not a plain object,
or, more cheeky option, do this:
- if there are any processing options set, attempt to parse the string, try-catch and throw a meaningful error message if it's not a JSON string; ELSE (no processing), pipe all inputs straight into
write-file-atomic
, skippingJSON.stringify
.
Arguments for the second option are the following.
-
Maybe somebody already has stringified JSON and just wants to write it do disk? Installing
write-file-atomic
as a new dependency is tedious, plus, it's a possible liability if directly tapped version ofwrite-file-atomic
mismatches the one thatwrite-json-file
uses. Promisifyingwrite-file-atomic
is another liability — what if user does not read the source and tap another promisifying library, other thanpify
? -
In
format-package
case where data is string, it would be terribly inefficient toJSON.parse
the data only to be right away stringified bywrite-json-file
. -
Second option is also more user-friendly: we could attempt to parse
data
(if processing is requested) and that would not require any extra dependencies.. And if there is no processing requested, we could cut corner and skipJSON.stringify
. -
Also, the first option would require plain object checks which is a new dependency like
lodash.isplainobject
. Going 2nd option route we avoid this, we just attempt to parse if string is given, elsethrow
. That's no extra dependencies.
Either way, even if we do nothing about this, at least let's write a unit test and cover the case, what happens when data
is: 1) empty string, 2) non-empty string but not JSON, 3) stringified valid JSON.