jow-/ucode

writefile() and readfile() compatibility

huafu opened this issue · 1 comments

huafu commented

Since fs.writefile() allows to JSON encode the data parameter if it's not a string, I think it'd be nice to have an optional parameter to fs.readfile so that it can be JSON decoded if that parameter is true:

import * as fs from 'fs';

let data = { key: "hello" };
fs.writefile('/tmp/file.json', data);

data = fs.readfile('/tmp/file.json', /* size */ null, /* as_json */ true);
print(type(data)); // object

data = fs.readfile('/tmp/file.json', /* size */ null, /* as_json */ false);
// or data = fs.readfile('/tmp/file.json');
print(type(data)); // string

PS: thanks for the quick slice() addition @jow- !

jow- commented

The writing of non-string values as JSON is not a specific property of fs.writefile() but due to the default stringification behavior - complex values are automatically converted to JSON strings.

Use json(fs.readfile('/tmp/file.json')) or json(fs.open('/tmp/file.json')) to read an input file as JSON. The latter variant is more efficient as it will do incremental parsing from the opened file handle internally (and auto-close it when done).