我使用下面的代码从本地系统读取文件:
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
进行操作,获取所需类型的数据和格式,然后可以使用render
和html
对其进行ejs
进行更多操作。在这里,我使用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');
虚拟输出:
关于javascript - 未捕获的TypeError : fs. readFileSync不是控制台中的函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43199224/