diff --git a/Readme.md b/Readme.md index 8cc396d..6391308 100644 --- a/Readme.md +++ b/Readme.md @@ -64,6 +64,32 @@ module.exports = { } ``` +### Same example with async `.json.js` file + +```js +// data.json.js + +var fs = require('fs') + +// If module exports a function, it becomes asynchronous. +// After all hard work it should send results to resolve function +module.exports = function (resolve) { + fs.readFile(__dirname + '/../../Readme.md', 'utf8', function (err, readme) { + readme = readme.split('\n')[0] // (just grab header for demo) + + // any other dependencies that are only used in here won't be included in bundle + var tape = require('tape') // some random dependency + + // Resulting object should be sent to resolve function + resolve({ + readme: readme, + tape: tape, // tape happens to be a function so it won't serialise. + random: Math.random(), // will be fixed to whatever value is generated at compile-time + }) + }) +} +``` + ```js // index.js console.log(require('./data.json.js')) diff --git a/index.js b/index.js index f64f9ba..0c0a4e2 100644 --- a/index.js +++ b/index.js @@ -1,9 +1,33 @@ 'use strict' module.exports = function toJSONLoader (code) { - return 'module.exports = ' + JSON.stringify(this.exec(code, this.resourcePath)) + '\n' + var result = this.exec(code, this.resourcePath) + + if (typeof result !== 'function') { + return toJSON(result) + } + + var callback = this.async() + if (!callback) { + if (result.sync) { + if (typeof result.sync === 'function') { + return toJSON(result.async()) + } else { + return toJSON(result.async) + } + } + this.emitError('Resource ' + this.resourcePath + ' needs async but it is not supported') + } + + result(function asyncCallback (result) { + callback(null, toJSON(result)) + }) } module.exports.pitch = function pitch () { this.clearDependencies() } + +function toJSON (result) { + return 'module.exports = ' + JSON.stringify(result) + '\n' +}