Skip to content

Commit

Permalink
feat: allow position offset as option
Browse files Browse the repository at this point in the history
  • Loading branch information
eliottvincent committed Oct 6, 2022
1 parent a082c71 commit a169cc5
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
9 changes: 9 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ describe('chardet', () => {
const res = await chardet.detectFile(path, { sampleSize: 32 });
expect(res).toBe('UTF-8');
});

it('should detect encoding with smaller sample size and position offset', async () => {
const res = await chardet.detectFile(path, { sampleSize: 32, position: 64 });
expect(res).toBe('UTF-8');
});
});

describe('#detectFileSync', () => {
Expand All @@ -50,6 +55,10 @@ describe('chardet', () => {
it('should detect encoding with smaller sample size', () => {
expect(chardet.detectFileSync(path, { sampleSize: 32 })).toBe('UTF-8');
});

it('should detect encoding with smaller sample size and position offset', () => {
expect(chardet.detectFileSync(path, { sampleSize: 32, position: 64 })).toBe('UTF-8');
});
});

describe('#analyse', () => {
Expand Down
7 changes: 4 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ import * as sbcs from './encoding/sbcs';
import * as iso2022 from './encoding/iso2022';

interface FullOptions {
sampleSize: number
sampleSize: number,
position: number
}

type Options = Partial<FullOptions>
Expand Down Expand Up @@ -107,7 +108,7 @@ export const detectFile = (filepath: string, opts: Options = {}): Promise<Detect
fd = fs.openSync(filepath, 'r');
const sample: Buffer = Buffer.allocUnsafe(opts.sampleSize);

fs.read(fd, sample, 0, opts.sampleSize, null, (err?: Error) => {
fs.read(fd, sample, 0, opts.sampleSize, opts.position, (err?: Error) => {
handler(err, sample);
});
return;
Expand All @@ -123,7 +124,7 @@ export const detectFileSync = (filepath: string, opts: Options = {}): DetectResu
const fd = fs.openSync(filepath, 'r');
const sample = Buffer.allocUnsafe(opts.sampleSize);

fs.readSync(fd, sample, 0, opts.sampleSize);
fs.readSync(fd, sample, 0, opts.sampleSize, opts.position);
fs.closeSync(fd);
return detect(sample);
}
Expand Down

0 comments on commit a169cc5

Please sign in to comment.