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?
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');