node.js 在打字稿中读取和写入文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33643107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:30:57  来源:igfitidea点击:

Read and write a text file in typescript

node.jstypescript

提问by william007

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 in accessing file system.

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

回答by basarat

believe there should be a way in accessing file system.

相信应该有一种访问文件系统的方法。

Include node.d.tsusing npm i @types/node. And then create a new tsconfig.jsonfile (npx tsc --init) and create a .tsfile as followed:

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

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

You can use other functions in fsas well : https://nodejs.org/api/fs.html

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

More

更多的

Node quick start : https://basarat.gitbooks.io/typescript/content/docs/node/nodejs.html

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

回答by Erik Lopez

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

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

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

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

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

获得文件后,只需.ts像这样添加对文件的引用:

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

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

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

然后,您可以使用节点文件系统模块编写可读写的打字稿类。您的打字稿类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();

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

一旦您将.ts文件转换为 javascript(如果您不知道如何操作,请查看此处),您可以使用 node 运行您的 javascript 文件并让魔术发挥作用:

> node myClass.js

回答by Ajinkya Kumbhar

import { readFileSync } from 'fs';

const file = readFileSync('./filename.txt', 'utf-8');

This worked for me. You may need to wrap the second command in any function or you may need to declare inside a class without keyword const.

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

回答by Andrei Bastos

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:

考虑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:

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

./
        filename.txt
        src

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

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

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

the __dirnameis directory name of the current module.

__dirname是当前模块的目录名。