User Tools

Site Tools


java-script:read-file

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
java-script:read-file [2023/08/04 23:31] odeftajava-script:read-file [2023/08/20 01:19] (current) – ↷ Links adapted because of a move operation 217.113.194.57
Line 103: Line 103:
 </code> </code>
  
 +===== Read a file in Node.js =====
  
 +First you should [[java-script:node-js:setup|initialize the directory as a node.js es6+ module.]]
  
 +<code javascript fileReader.js>
 +import fs from 'fs/promises';
 +
 +export async function readFile(filePath) {
 +    try {
 +        const data = await fs.readFile(filePath, 'utf8');
 +        console.log('File content:', data);
 +    } catch (err) {
 +        console.error('An error occurred:', err);
 +    }
 +}
 +</code>
 +
 +<code javascript index.js>
 +import { readFile } from './fileReader.js';
 +
 +const fileName = process.argv[2];
 +if (!fileName) {
 +    console.log('Please provide a file name as a command-line argument');
 +    process.exit(1);
 +}
 +
 +readFile(fileName);
 +</code>
 +
 +To run it:
 +<code>
 +node ./index.js C:/test.txt
 +</code>
  
  
  
  
java-script/read-file.1691181076.txt.gz · Last modified: 2023/08/04 23:31 by odefta