Read and write a text file in typescript

前端 未结 4 2117
暖寄归人
暖寄归人 2020-12-10 00:39

How should I read and write a text file from typescript in node.js? I am not sure would read/write a file be sandboxed in node.js, if not, i believe there should be a way i

4条回答
  •  长情又很酷
    2020-12-10 01:14

    import * as fs from 'fs';
    import * as path from 'path';
    
    fs.readFile(path.join(__dirname, "filename.txt"), (err, data) => {
        if (err) throw err;
        console.log(data);
    })
    
    

    EDIT:

    consider the project structure:

    ../readfile/
    ├── filename.txt
    └── src
        ├── index.js
        └── index.ts
    

    consider the index.ts:

    import * as fs from 'fs';
    import * as path from 'path';
    
    function lookFilesInDirectory(path_directory) {
        fs.stat(path_directory, (err, stat) => {
            if (!err) {
                if (stat.isDirectory()) {
                    console.log(path_directory)
                    fs.readdirSync(path_directory).forEach(file => {
                        console.log(`\t${file}`);
                    });
                    console.log();
                }
            }
        });
    }
    
    let path_view = './';
    lookFilesInDirectory(path_view);
    lookFilesInDirectory(path.join(__dirname, path_view));
    

    if you have in the readfile folder and run tsc src/index.ts && node src/index.js, the output will be:

    ./
            filename.txt
            src
    
    /home/andrei/scripts/readfile/src/
            index.js
            index.ts
    

    that is, it depends on where you run the node.

    the __dirname is directory name of the current module.

提交回复
热议问题