150

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
escplat12
  • 2,191
  • 4
  • 22
  • 34
  • 1
    A transpiler. Or the next node release from the future. – Bergi Apr 25 '17 at 23:04
  • Look at my answer to get it working! – nomis Sep 04 '18 at 22:37
  • 1
    While Node 14 allows (for example) `import fs from 'fs/promises'` syntax, on earlier versions, you'll have to create an alias using `import { promises as fs } from syntax` – imrok Jan 27 '21 at 09:07

11 Answers11

185

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
RobertoNovelo
  • 3,347
  • 3
  • 21
  • 32
  • 20
    This does not work because fs has neither a default export nor an export named "fs". `import fs from "fs";` is the correct syntax. – Konrad Höffner Oct 17 '19 at 08:07
  • 2
    How can this incorrect answer have so many upvotes? Please update this answer in accordance with the comment from @KonradHöffner above. – rinogo Dec 16 '21 at 17:34
  • 3
    @rinogo Callback and async APIs are imported via `import * as fs from 'fs';`, and the promise-based APIs via `import * as fs from 'fs/promises';`. `fs` supports both CommonJS syntax and ES6 Modules. Can you provide an example usage with `import fs from "fs";` ? Also, the rest of the answer is just an example of how you can export/import functions and defaults. – RobertoNovelo Dec 18 '21 at 03:23
  • @RobertoNovelo Yeah, I'm not sure what's going on - on second look, I *am* using the syntax you've recommended. However, I clearly felt strong enough to upvote Konrad's comment and add a comment of my own... I remember getting a syntax error in Typescript with the syntax that I'm clearly using now. I'm digging in at the moment and will report back if I figure out what's going on. – rinogo Dec 18 '21 at 14:33
  • Getting this error Uncaught TypeError: Failed to resolve module specifier "fs". Relative references must start with either "/", "./", or "../". –  Nov 23 '22 at 09:14
  • @HarshShukla are you using `import * as fs from 'fs';`? Are you running it on any special runtime such as an edge function? If so, the `fs` module might not be available unless the platform provides it for you. Additionally, `fs` is a node.js module, importing it in the front end will not work natively. – RobertoNovelo Nov 23 '22 at 18:19
  • This is a bad answer because you are giving just general advice and not addressing the specific problem. Because of that it's even misleading and just wastes time. – NickJ Apr 25 '23 at 20:40
75

ES6 modules support in Node.js is fairly recent; even in the bleeding-edge versions, it is still experimental. With Node.js 10, you can start Node.js with the --experimental-modules flag, and it will likely work.

To import on older Node.js versions - or standard Node.js 10 - use CommonJS syntax:

const fs = require('fs');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
phihag
  • 278,196
  • 72
  • 453
  • 469
55

Building on RobertoNovelo's answer:

import * as fs from 'fs';

is currently the simplest way to do it.

It was tested with a Node.js project (Node.js v10.15.3), with esm, allowing to use import.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Yoann
  • 693
  • 5
  • 6
40

In order to use import { readFileSync } from 'fs', you have to:

  1. Be using Node.js 10 or later
  2. Use the --experimental-modules flag (in Node.js 10), e.g. node --experimental-modules server.mjs (see #3 for explanation of .mjs)
  3. Rename the file extension of your file with the import statements, to .mjs, .js will not work, e.g. server.mjs

The other answers hit on 1 and 2, but 3 is also necessary. Also, note that this feature is considered extremely experimental at this point (1/10 stability) and not recommended for production, but I will still probably use it.

Here's the Node.js 10 ESM documentation.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
nomis
  • 1,582
  • 14
  • 14
8

Go to package.json file and add:

"type": "module"

This worked for me!

1

If we are using TypeScript, we can update the type definition file by running the command npm install @types/node from the terminal or command prompt.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rajkumar Peter
  • 871
  • 8
  • 7
0

The new ECMAScript module support is able natively in Node.js 12

It was released on 2019-04-23 and it means there is no need to use the flag --experimental-modules.

To read more about it:

The new ECMAScript module support in Node.js 12

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
José Silva
  • 361
  • 1
  • 12
0

If you want your statement import fs from 'fs' to be executable, you can make your file extension .mjs instead of .js. i.e filename.mjs

Simba
  • 35
  • 4
-1

It's not supported just yet... If you want to use it you will have to install Babel.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SakoBu
  • 3,972
  • 1
  • 16
  • 33
-1

hey friends node js use commonjs not modaljs so use alawys use const fs = require('fs') for file system if we use modaljs import fs from 'fs' its give error se in termile import {fs} from 'fs'; ^^^^^^ SyntaxError: Cannot use import statement outside a module

Usama ijaz
  • 21
  • 2
-1

It is 2023, In the current version node 16+:

import {readFileSync} from "fs"

const string_output = readFileSync("path-to-file", 'utf8')
// the rest

If you do not give the second argument, encoding 'utf8', it will return a binary file

Ali Khosro
  • 1,580
  • 18
  • 25