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

Custom processor with two arguments #186

Merged
merged 7 commits into from
Feb 14, 2024
Merged
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
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