Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add async execution ability #3

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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'))
Expand Down
26 changes: 25 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -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'
}