java-script:read-file
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
java-script:read-file [2023/08/04 23:30] – odefta | java-script:read-file [2023/08/20 01:19] (current) – ↷ Links adapted because of a move operation 217.113.194.57 | ||
---|---|---|---|
Line 61: | Line 61: | ||
If you prefer using **Promise** instead of the **onload** event, you can create a wrapper function around the FileReader API that returns a promise. \\ | If you prefer using **Promise** instead of the **onload** event, you can create a wrapper function around the FileReader API that returns a promise. \\ | ||
- | A new function readAsText wraps the FileReader API and returns a promise. This promise resolves with the file's contents when the onload event is fired, and rejects if there' | + | A new function |
<code javascript read-file-web-promise.html> | <code javascript read-file-web-promise.html> | ||
Line 103: | Line 103: | ||
</ | </ | ||
+ | ===== Read a file in Node.js ===== | ||
+ | First you should [[java-script: | ||
+ | <code javascript fileReader.js> | ||
+ | import fs from ' | ||
+ | |||
+ | export async function readFile(filePath) { | ||
+ | try { | ||
+ | const data = await fs.readFile(filePath, | ||
+ | console.log(' | ||
+ | } catch (err) { | ||
+ | console.error(' | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | <code javascript index.js> | ||
+ | import { readFile } from ' | ||
+ | |||
+ | const fileName = process.argv[2]; | ||
+ | if (!fileName) { | ||
+ | console.log(' | ||
+ | process.exit(1); | ||
+ | } | ||
+ | |||
+ | readFile(fileName); | ||
+ | </ | ||
+ | |||
+ | To run it: | ||
+ | < | ||
+ | node ./index.js C:/test.txt | ||
+ | </ | ||
java-script/read-file.1691181029.txt.gz · Last modified: 2023/08/04 23:30 by odefta