I have a JavaScript object that contains functions and special values like Infinity, as well as strings and numbers:
const myObject = {
propertyA: "my string",
propertyB: 5,
propertyC: () => "function returing a string",
propertyD: Infinity
};
I would like to save it to a file so that the resulting content looks like this:
export default function () {
return {
propertyA: "my string",
propertyB: 5,
propertyC: () => "function returing a string",
propertyD: Infinity
};
}
I have tried to use JSON.stringify(), but that doesn't work with functions and special values, as those are not valid JSON:
writeFileSync('my-output.js', `
export default function () {
return ${ JSON.stringify(myObject) };
}
`);
const myObject = {
propertyA: "my string",
propertyB: 5,
propertyC: () => "function returing a string",
propertyD: Infinity
};
console.log(JSON.stringify(myObject, null, 4));
Is there any other way to do this?