Read and write a text file in typescript

前端 未结 4 2120
暖寄归人
暖寄归人 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:07

    First you will need to install node definitions for Typescript. You can find the definitions file here:

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

    Once you've got file, just add the reference to your .ts file like this:

    ///

    Then you can code your typescript class that read/writes, using the Node File System module. Your typescript class myClass.ts can look like this:

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

    Once you transpile your .ts file to a javascript (check out here if you don't know how to do it), you can run your javascript file with node and let the magic work:

    > node myClass.js
    

提交回复
热议问题