Using import fs from 'fs'
Asked Answered
D

11

171

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?

Downbeat answered 25/4, 2017 at 23:1 Comment(3)
A transpiler. Or the next node release from the future.Permittivity
Look at my answer to get it working!Fideicommissum
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 syntaxDichy
D
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');
Durkee answered 25/4, 2017 at 23:8 Comment(2)
The answer from RobertoNovelo would be the better choice if you really want to use ES6 imports.Ungenerous
You can use --experimental-modules from node v8.5. nodejs.org/docs/latest-v8.x/api/esm.htmlGregoriagregorian
V
208

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

Valvate answered 25/4, 2017 at 23:7 Comment(7)
This does not work because fs has neither a default export nor an export named "fs". import fs from "fs"; is the correct syntax.Costly
How can this incorrect answer have so many upvotes? Please update this answer in accordance with the comment from @KonradHöffner above.Airliner
@Airliner 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.Valvate
@Valvate 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.Airliner
Getting this error Uncaught TypeError: Failed to resolve module specifier "fs". Relative references must start with either "/", "./", or "../".Finish
@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.Valvate
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.Wolfort
D
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');
Durkee answered 25/4, 2017 at 23:8 Comment(2)
The answer from RobertoNovelo would be the better choice if you really want to use ES6 imports.Ungenerous
You can use --experimental-modules from node v8.5. nodejs.org/docs/latest-v8.x/api/esm.htmlGregoriagregorian
D
60

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.

Disbud answered 7/5, 2019 at 8:44 Comment(1)
I've v10.16.0 and it doesn't work for me giving error- unexpected token *Bathetic
F
42

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.

Fideicommissum answered 30/8, 2018 at 21:15 Comment(0)
B
9

Go to package.json file and add:

"type": "module"

This worked for me!

Bono answered 13/6, 2021 at 3:29 Comment(0)
P
6

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

Phonics answered 22/4, 2023 at 17:48 Comment(0)
I
2

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.

Irritability answered 28/6, 2019 at 17:34 Comment(0)
F
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

Ferromanganese answered 24/4, 2019 at 17:6 Comment(1)
This is not true, in node v12.11.1 the flag is still required.Costly
G
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

Glimpse answered 17/8, 2022 at 5:15 Comment(0)
D
-1

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

Doall answered 16/6, 2017 at 2:29 Comment(0)
C
-2

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

Clem answered 1/3, 2022 at 6:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.