Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using import fs from 'fs'

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?

like image 882
birdybird03 Avatar asked Apr 25 '17 23:04

birdybird03


People also ask

How do I import a module in fs?

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.

How do you use fs modules?

To include the File System module, use the require() method: var fs = require('fs'); Common use for the File System module: Read files.

Do I need to install fs module?

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.


1 Answers

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

like image 150
RobertoNovelo Avatar answered Sep 28 '22 08:09

RobertoNovelo