为什么 import * as fs from 'fs' 不起作用并给我一个错误?

问题描述 投票:0回答:1

** 更新 **

原来我当时不太知道普通JS和Node JS有什么区别,但是你所要做的就是安装npm包

npm install fs
然后使用
node <filname>
,记住你不能使用
document.getElementById
或其他什么,如果你想这样做,你必须使用
cors
express
使其成为服务器,这样你就可以使用常规 JS 获取该数据!希望这有帮助!

所以这是我的问题:

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)

但是我得到 Uncaught SyntaxError: Cannot use import statements Outside a module 错误

我试图从文件中读取,但我不能!

我到处搜索,但找不到我的解决方案。

javascript import requirejs node.js-fs
1个回答
3
投票

由于您正在编写 CommonJS (CJS),因此只需删除

import * as fs from 'fs';
行(即 ESM 语法)即可。您需要导入
fs
的唯一一行是:
const fs = require('fs')
,您已经拥有了。

如果您想使用

import
样式语法 (ESM),请将
"type": "module",
添加到
package.json
并删除
const fs = require('fs')
行。

© www.soinside.com 2019 - 2024. All rights reserved.