简体   繁体   English

使用Typescript在nodejs中读取文件

[英]readFile in nodejs with Typescript

I start to learn typescript today, and there's a problem. 我今天开始学习打字稿,但是有一个问题。

Here is the filetree(after compiling): 这是文件树(编译后):

dist dist
index.js index.js
src src
data.txt data.txt
index.ts 索引

Here is ./src/index.ts: 这是./src/index.ts:

import { readFileSync } from 'fs';

let data = readFileSync('./data.txt');
console.log(data);

After compiling with command "tsc", it creates ./dist/index.js, absolutely the file data.txt cannot be read correctly. 使用命令“ tsc”编译后,它将创建./dist/index.js,绝对不能正确读取文件data.txt。 How to make it the right path? 如何使其走上正确的道路?

Usually you are not supposed to put data in src folder. 通常,您不应该将数据放在src文件夹中。 There are several ways if you really want to do so: 如果您确实想这样做,可以采用以下几种方法:

  1. copy data.txt to dist while compiling typescript 在编译打字稿时将data.txt复制到dist
  2. use absolute path which could be path.join(__dirname, "../src/data.txt") 使用绝对路径,可以是path.join(__dirname, "../src/data.txt")
  3. Since you already know index.ts is going to be compiled to dist, use "../src/data.txt" directly 因为您已经知道index.ts将被编译为dist, "../src/data.txt"直接使用"../src/data.txt"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM