typescript 读写文件-在打字稿中读取和写入文本文件

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

获得文件后typescript 读写文件,将引用添加到 .ts 文件,如下所示:

typescript 读写文件-在打字稿中读取和写入文本文件

///

然后,您可以使用节点文件系统模块编写读/写打字稿类。 你的 TypeScript 类 myClass.ts 看起来像这样:

typescript 读写文件-在打字稿中读取和写入文本文件

/// <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();

typescript 读写文件-在打字稿中读取和写入文本文件

将 .ts 文件转换为 javascript 后(如果您不知道如何操作,请查看此处)typescript 读写文件,您可以使用 Node 运行 javascript 文件并让魔法发挥作用:

> node myClass.js

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悟空资源网 typescript typescript 读写文件-在打字稿中读取和写入文本文件 https://www.wkzy.net/game/183220.html

常见问题

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务