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 20:31] – odefta | java-script:read-file [2025/01/02 18:22] (current) – external edit 127.0.0.1 | ||
|---|---|---|---|
| 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.1691181076.txt.gz · Last modified: (external edit)
