Skip to content

Commit

Permalink
Custom processor with two arguments (#186)
Browse files Browse the repository at this point in the history
* Custom processor with additional argument which receives the file being processed

* Update lib/process-file.spec.js

Co-authored-by: Adam Reis <[email protected]>

* Update lib/process-file.spec.js

Co-authored-by: Adam Reis <[email protected]>

* Update lib/helpers/run-processors.js

Co-authored-by: Adam Reis <[email protected]>

* Update README.md

Co-authored-by: Adam Reis <[email protected]>

* Update README.md

Co-authored-by: Adam Reis <[email protected]>

* cleanup

---------

Co-authored-by: Kevin Sommer <[email protected]>
Co-authored-by: Adam Reis <[email protected]>
  • Loading branch information
3 people authored Feb 14, 2024
1 parent 3b936d9 commit e90c51f
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,14 @@ const results = replace.sync({
processor: (input) => input.replace(/foo/g, 'bar'),
});
```
The custom processor will receive the path of the file being processed as a second parameter:

```js
const results = replace.sync({
files: 'path/to/files/*.html',
processor: (input, file) => input.replace(/foo/g, file),
});
```

### Array of custom processors

Expand Down
2 changes: 1 addition & 1 deletion lib/helpers/run-processors.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ module.exports = function runProcessors(contents, processor, file) {
const result = {file};

const newContents = processors.reduce((contents, processor) => {
return processor(contents);
return processor(contents, file);
}, contents);

result.hasChanged = (newContents !== contents);
Expand Down
19 changes: 19 additions & 0 deletions lib/process-file.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,13 @@ describe('Process a file', () => {
return config;
}

function appendFileProcessor(config) {
config.processor = (content, file) => {
return `${content}${file}`;
};
return config;
}

/**
* Async with promises
*/
Expand Down Expand Up @@ -754,6 +761,18 @@ describe('Process a file', () => {
expect(results[2].hasChanged).to.equal(false);
});

it('should pass filename to processor as second parameter', () => {
transform.sync(appendFileProcessor({
files: 'test*',
}));
const test1 = fs.readFileSync('test1', 'utf8');
const test2 = fs.readFileSync('test2', 'utf8');
const test3 = fs.readFileSync('test3', 'utf8');
expect(test1).to.equal(`${testData}test1`);
expect(test2).to.equal(`${testData}test2`);
expect(test3).to.equal('nopetest3');
});

describe('fs', () => {
it('reads and writes using a custom fs when provided', done => {
const before = 'a';
Expand Down

0 comments on commit e90c51f

Please sign in to comment.