【问题标题】:Read and write a text file in typescript在打字稿中读取和写入文本文件
【发布时间】:2016-02-12 02:30:54
【问题描述】:

我应该如何在 node.js 中从 typescript 读取和写入文本文件? 我不确定是否会在 node.js 中对文件进行沙盒读取/写入,如果没有,我相信应该有一种访问文件系统的方法。

【问题讨论】:

    标签: node.js typescript


    【解决方案1】:

    相信应该有办法访问文件系统。

    使用npm i @types/node 包含node.d.ts。然后新建一个tsconfig.json文件(npx tsc --init)并创建一个.ts文件如下:

    import * as fs from 'fs';
    fs.readFileSync('foo.txt','utf8');
    

    您也可以使用fs 中的其他功能:https://nodejs.org/api/fs.html

    更多

    节点快速入门:https://basarat.gitbooks.io/typescript/content/docs/node/nodejs.html

    【讨论】:

    • 使用您的代码我收到错误 TS2307:找不到模块“fs”。节点 v.6.4.0 和 tsc v.1.8.10。你有什么建议吗?
    • @WorkingMatt npm install --save-dev @types/node
    • 我们为什么在这里使用require而不是import?
    • @PrimeByDesign 只是一个非常古老的答案。更新了最新技术?
    • 使用 ES6 语法将是 import * as fs from 'fs';
    【解决方案2】:

    首先,您需要为 Typescript 安装 node 定义。您可以在此处找到定义文件:

    https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/node.d.ts

    获得文件后,只需将引用添加到您的 .ts 文件,如下所示:

    /// <reference path="path/to/node.d.ts" />

    然后,您可以使用 Node File System 模块编写读/写的 typescript 类。你的 typescript 类 myClass.ts 可以如下所示:

    /// <reference path="path/to/node.d.ts" />
    
    class MyClass {
    
        // Here we import the File System module of node
        private fs = require('fs');
    
        constructor() { }
    
        createFile() {
    
            this.fs.writeFile('file.txt', 'I am cool!',  function(err) {
                if (err) {
                    return console.error(err);
                }
                console.log("File created!");
            });
        }
    
        showFile() {
    
            this.fs.readFile('file.txt', function (err, data) {
                if (err) {
                    return console.error(err);
                }
                console.log("Asynchronous read: " + data.toString());
            });
        }
    }
    
    // Usage
    // var obj = new MyClass();
    // obj.createFile();
    // obj.showFile();
    

    一旦您将.ts 文件转换为 javascript(check out here,如果您不知道该怎么做),您可以使用 node 运行您的 javascript 文件并让魔法发挥作用:

    > node myClass.js
    

    【讨论】:

    • 可以使用npm i --save @types/node安装节点类型
    【解决方案3】:
    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);
    })
    
    

    编辑:

    考虑项目结构:

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

    考虑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));
    

    如果你在 readfile 文件夹中运行tsc src/index.ts &amp;&amp; node src/index.js,输出将是:

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

    也就是说,这取决于您运行节点的位置。

    __dirname 是当前模块的目录名。

    【讨论】:

    【解决方案4】:
    import { readFileSync } from 'fs';
    
    const file = readFileSync('./filename.txt', 'utf-8');
    

    这对我有用。 您可能需要将第二个命令包装在任何函数中,或者您可能需要在没有关键字 const 的类中声明。

    【讨论】:

      【解决方案5】:

      澄清一下:如果出现 TS 2307:找不到模块导入错误:检查 tsconfig.json 文件。

      它必须包含 node_modules

      {
      .....
        "include": [
          "src/**/*.ts",
          "src/**/*.tsx",
          "src/**/*.vue",
          "tests/**/*.ts",
          "tests/**/*.tsx",
          "node_modules"
        ],
      .....
      }
      

      【讨论】:

        【解决方案6】:

        我遇到“找不到模块'fs'或其对应的类型声明”时

        import { readFileSync } from 'fs';
        

        我如何解决它

        与杰罗姆·维利塞克的回答有点偏差

        编辑 tsconfig.app.json:

        ...
        "include": [
            "src/**/*.d.ts",
            "node_modules/@types/node/"
        ]
        ...
        

        【讨论】:

          猜你喜欢
          • 2021-08-22
          • 2016-10-06
          • 2020-02-20
          • 2014-07-28
          • 2012-09-15
          • 2020-10-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多