Using import fs from 'fs'
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.jsexport 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 function1function1();function2();
Additionally, you should use Webpack or something similar to be able to use ES6 import
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');
In order to use import { readFileSync } from 'fs'
, you have to:
- Be using Node.js 10 or later
- Use the
--experimental-modules
flag (in Node.js 10), e.g.node --experimental-modules server.mjs
(see #3 for explanation of .mjs) - 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.