Search code examples
javascriptimportrequirejsnode.js-fs

Why the import * as fs from 'fs' doesn't work and gives me an error?


So this is my problem:

import * as fs from 'fs';

var downloads = 0;

const fs = require('fs')
fs.readFile('tp.txt', (err, inputD) => {
   if (err) throw err;
      downloads = inputD.toString();
})

setInterval(function (){
    fs.readFile('tp.txt', (err, inputD) => {
        if (err) throw err;
           downloads = inputD.toString();
     })
    document.getElementById("downloads").innerText = downloads;
}, 5000)

But I get Uncaught SyntaxError: Cannot use import statement outside a module error

I was trying to read from a file but I couldn't!

I searched everywhere but I can't find my soulution.


Solution

  • Since you are writing CommonJS (CJS), you can just remove the import * as fs from 'fs'; line (that is ESM syntax). The only line you need to import fs is this one: const fs = require('fs'), which you already have.

    If you want to use import-style syntax (ESM), add "type": "module", to your package.json and remove the const fs = require('fs') line instead.