![](/img/trans.png)
[英]Uncaught TypeError: fs.readFileSync is not a function error in browser console
[英]Uncaught TypeError: fs.readFileSync is not a function in console
我使用以下代码从本地系统读取文件:
var fs = require('fs');
var text = fs.readFileSync("./men.text");
var textByLine = text.split("\n")
console.log(textByLine);
注意: fs
是一个nodejs模块,您不能在浏览器中使用它。
导入fs模块,
readFileSync
将为您提供缓冲区
要使用split()
函数,您必须将Buffer
转换为String
var fs = require('fs')
var text = fs.readFileSync("./men.text");
var string = text.toString('utf-8') // converting the Buffer into String
var textByLine = string.split("\n")
console.log(textByLine);
▼ 更新 ▼
服务器端
fs
是一个nodejs内置模块,您不能在Browser(Client-Side)中使用它。 在服务器端使用fs
进行操作,获取所需类型的数据和格式,然后可以使用html
, ejs
进行render
。
在这里,我使用express创建了一个Nodejs服务器,然后从浏览器中访问http://localhost:8000/
您将获得数据数组
您可以格式化你的数据,并与使其.ejs
或html
使用文件res.render
app.js
var express = require('express');
var app = express();
var fs = require('fs')
app.get('/', function (request, response) {
var text = fs.readFileSync("./men.text");
var string = text.toString('utf-8')
var textByLine = string.split("\n")
console.log(textByLine);
response.send(textByLine);
});
app.listen('8000');
虚拟输出:
对于仍在eletron应用程序上获得未定义功能的所有人:
解决方案(至少对我而言)是不这样做:
const fs = require('fs');
我做了:
const fs = window.require('fs');
这样就解决了我遇到的所有问题。
var fs = require('fs');
var text = fs.readFileSync('./men.text', 'utf8');
var textByLine = text.split("\n");
console.log(textByLine);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.