I want to use import fs from 'fs'
in JavaScript. Here is a sample:
import fs from 'fs' var output = fs.readFileSync('someData.txt') console.log(output)
The error I get when I run my file using node main.js
is:
(function (exports, require, module, __filename, __dirname) { import fs from 'fs ' ^^^^^^ SyntaxError: Unexpected token import
What should I install in Node.js in order to achieve importing modules and functions from other places?
To import and use the fs module in TypeScript, make sure to install the type definitions for node by running npm i -D @types/node and import fs with the following line import * as fs from 'fs' , or import { promises as fsPromises } from 'fs' if using fs promises.
To include the File System module, use the require() method: var fs = require('fs'); Common use for the File System module: Read files.
This module is for handling the file system, as fs stands for the file system. There is no need to install this module, as it is available as a built-in module that comes with the installation of Node.
For default exports you should use:
import * as fs from 'fs';
Or in case the module has named exports:
import {fs} from 'fs';
Example:
//module1.js export function function1() { console.log('f1') } export function function2() { console.log('f2') } export default function1;
And then:
import defaultExport, { function1, function2 } from './module1' defaultExport(); // This calls function1 function1(); function2();
Additionally, you should use Webpack or something similar to be able to use ES6 import
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With