gpt4 book ai didi

javascript - 未捕获的类型错误 : fs. readFileSync 不是控制台中的函数

转载 作者:太空宇宙 更新时间:2023-11-03 23:02:45 25 4
gpt4 key购买 nike

我使用以下代码从本地系统读取文件:

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内置模块,您不能在浏览器(客户端)中使用它。在服务器端使用fs进行操作,获取所需类型的数据和格式,然后您可以使用htmlejs等等进行渲染..模板引擎

这里我使用express创建了一个Nodejs服务器,从浏览器中点击http://localhost:8000/你将获得数据数组

您可以格式化数据并使用 res.render 将其呈现为 .ejshtml 文件

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');
<小时/>

虚拟输出:

enter image description here

关于javascript - 未捕获的类型错误 : fs. readFileSync 不是控制台中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43199224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com