js 如何将 {a:[Function()]} 写入文件?-灵析社区

小飞侠007

我现在是将方法`A`定义在被写入的文件里,然后 `{a:'${A}'}`,在写入之前将`'${}'`,给删了;但有没有简洁一点的方法呢? function A( ) { console.log(1); } function process() { ... } fs.writeFile(..., process( {a : A} ) , ...); `process` 如何编写?

阅读量:368

点赞量:12

问AI
const fs = require('fs'); function A() { console.log(1); } function process(obj) { return JSON.stringify(obj, function(key, value) { if (typeof value === 'function') { return value.toString(); } return value; }); } fs.writeFile('output.json', process({ a: A }), (err) => { if (err) throw err; console.log('The file has been saved!'); }); 没错: const fs = require('fs'); function A() { console.log(1); } function process(obj) { const entries = Object.entries(obj).map(([key, value]) => { if (typeof value === 'function') { return `${key}: ${value.toString()}`; } return `${key}: ${JSON.stringify(value)}`; }); return `{ ${entries.join(', ')} }`; } fs.writeFile('output.js', process({ a: A }), (err) => { if (err) throw err; console.log('The file has been saved!'); }); 用的时候: const obj = require('./output.js'); obj.a();