Use fs in typescript
Latest implantation, you can import methods.
import { readFile, writeFile } from 'fs/promises';
And use directly...
// write
await writeFile('./file.json', content);
// read
const content = await readFile('./file.json');
Reference https://nodejs.org/docs/latest-v14.x/api/
I can't imagine any case in which you would use fs
inside a React component. Even though you can use React in the server to render stuff, the same code is supposed to run in the client, there's no way you can access fs
in the client.
If you want to use fs
in the server, this is an example:
import * as fs from 'fs';
import * as path from 'path';
fs.readFile(path.join(__dirname, '../../client/index.html'), 'utf8', (error, data) => {
// ...
})
On your package.json
file, make sure to have a dependency on node
"dependencies": {
"@types/node": "^7.0.5"
}
And this is how my tsconfig.json
file looks like:
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es5",
"jsx": "react",
"allowJs": true,
"typeRoots": [
"./node_modules/@types"
]
},
"include": [
"./db/**/*",
"./src/**/*"
]
}
Using node -v 10.15.0
and @types/node:
It seems declaration has been rewritten...
fs
definition is declared as a module
so you should do:
import fs from "fs"; // Without star
compiled:
var fs_1 = __importDefault(require("fs"));
or
const fs = require("fs");
instead of require("fs").default;
with star you will have fs.default.TheFunctionYouWant
instead of fs.TheFunctionYouWant
The better way is to console.log(fs);
to see what it is imported.
{
"compilerOptions": {
"typeRoots": [],
"types": [
"node"
]
}
}