[英]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.