繁体   English   中英

如何使用 Node.js 读取不同名称的文件?

[英]How to read Files with different names with Node.js?

我有一个包含 HTML 个文件的文件夹,这些文件有 2 个不同的类别。 其中之一是名为 arq.html 的主页,其中包含所有其他页面的索引。 所有其他页面都包含有关特定个人的实际信息,名称为 arqx.html,其中 x 对应于页面编号。

我想要做的是能够单击索引和 go 进入相应的 HTML 页面。 这些索引中的每一个都有 URL localhost:7777/arq/x。

例如 localhost:7777/arq/7 应该用 arq7.html 文件来回答。

目前我有以下代码:

var http = require('http')
var fs = require('fs')

http.createServer(function (req, res){
    var num = req.url.split("/")[req.url.length-1]
    fs.readFile('arq' + num +'.html', function(err, data) {
        res.writeHead(200, {'Content-Type': 'text/html'})
        res.write(data)
        res.end()
    })
    
}).listen(7777);
console.log('Servidor à escuta na porta 7777...')

var num是我看到的用来解析 URL 的东西,所以我可以获得实际的 x。 我不确定是不是解析有误,还是我弄乱了文件位置。

另外,我得到的错误:

_http_outgoing.js:696
    throw new ERR_INVALID_ARG_TYPE('first argument',
    ^

TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer or Uint8Array. Received undefined
    at write_ (_http_outgoing.js:696:11)
    at ServerResponse.write (_http_outgoing.js:661:15)
    at ReadFileContext.callback (C:\Users\joao_\OneDrive\Ambiente de Trabalho\dataset\server1.js:8:13)
    at FSReqCallback.readFileAfterOpen [as oncomplete] (fs.js:273:13) {
  code: 'ERR_INVALID_ARG_TYPE'
}

您应该使用console.log(data)来查看您得到的不是字符串或缓冲区的内容。

您还应该查看err以确定读取文件时是否有错误。

在这种情况下,存在错误,因此dataundefined

该错误是由于您输入错误的文件名引起的。

 req.url.split("/")[req.url.length-1]

req.url.split("/")给你一个数组,但这不是你正在阅读的.length req.url

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM