只想在网络浏览器上显示我的node.js结果.. 有可能吗?...
这是我的代码:
const testFolder = 'texts/';
const fs = require('fs');
fs.readdirSync(testFolder).forEach(file => {
console.log(file);
})
当我尝试在cmd上运行该代码时,它可以工作。代码获取特定目录中的所有.txt文件。
结果如下:
然后,当我试图在我的浏览器上加载它时,结果是这样的
我也计划在node.js代码修复后将所有结果文件名添加到数据库mysql中。这也是可能的吗?..
谢谢..这是我第一次创建node.js
答案 0 :(得分:1)
使用快速路由器接受来自浏览器的GET
请求:
const express = require('express');
const fs = require('fs');
const app = express();
const testFolder = 'texts/';
// To set your public directory and use relative url
app.use(express.static(__dirname + 'your_public_dir'));
// When you access to localhost:8080, it will send GET '/' request
app.get('/', function(req,res) {
fs.readdirSync(testFolder).forEach(file => {
console.log(file);
});
});
答案 1 :(得分:1)
npm install --save express
但是,您还需要写入服务器的响应,以便在网站上显示。例如,使用Express:
app.get('/', function(req,res) {
res.write("whatever you want to display");
res.end()
});