This repository has been archived by the owner on Apr 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #60 from AtkinsSJ/read-lines
Extract code for reading a line at a time, from head/tail/wc builtins
- Loading branch information
Showing
4 changed files
with
54 additions
and
80 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
import { resolveRelativePath } from './path.js'; | ||
|
||
// Iterate the given file, one line at a time. | ||
// TODO: Make this read one line at a time, instead of all at once. | ||
export async function* fileLines(ctx, relPath, options = { dashIsStdin: true }) { | ||
let lines = []; | ||
if (options.dashIsStdin && relPath === '-') { | ||
lines = await ctx.externs.in_.collect(); | ||
} else { | ||
const absPath = resolveRelativePath(ctx.vars, relPath); | ||
const fileData = await ctx.platform.filesystem.read(absPath); | ||
if (fileData instanceof Blob) { | ||
const arrayBuffer = await fileData.arrayBuffer(); | ||
const fileText = new TextDecoder().decode(arrayBuffer); | ||
lines = fileText.split(/\n|\r|\r\n/).map(it => it + '\n'); | ||
} else if (typeof fileData === 'string') { | ||
lines = fileData.split(/\n|\r|\r\n/).map(it => it + '\n'); | ||
} else { | ||
// ArrayBuffer or TypedArray | ||
const fileText = new TextDecoder().decode(fileData); | ||
lines = fileText.split(/\n|\r|\r\n/).map(it => it + '\n'); | ||
} | ||
} | ||
|
||
for (const line of lines) { | ||
yield line; | ||
} | ||
} |