简体   繁体   English

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

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

I have a folder with HTML files that have 2 different categories.我有一个包含 HTML 个文件的文件夹,这些文件有 2 个不同的类别。 One of them is the Main Page called arq.html which has the indexes of every other page.其中之一是名为 arq.html 的主页,其中包含所有其他页面的索引。 All of the other pages contain the actual information about a specific individual and have the name of arqx.html where x corresponds to the number of the page.所有其他页面都包含有关特定个人的实际信息,名称为 arqx.html,其中 x 对应于页面编号。

What I'm trying to do is to be able to click an index and go into the respective HTML page.我想要做的是能够单击索引和 go 进入相应的 HTML 页面。 Each of these indexes has the URL localhost:7777/arq/x.这些索引中的每一个都有 URL localhost:7777/arq/x。

For example localhost:7777/arq/7 should answer with the arq7.html file.例如 localhost:7777/arq/7 应该用 arq7.html 文件来回答。

At the moment I have the following code:目前我有以下代码:

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...')

The var num was something I saw to parse the URL so I could obtain the actual x. var num是我看到的用来解析 URL 的东西,所以我可以获得实际的 x。 I'm not sure if it's the parsing that's wrong, or if I'm messing something up with the files locations.我不确定是不是解析有误,还是我弄乱了文件位置。

Also, the error I'm getting:另外,我得到的错误:

_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'
}

You should console.log(data) to see what you are getting which isn't a string or a buffer.您应该使用console.log(data)来查看您得到的不是字符串或缓冲区的内容。

You should also look at err to find out if there was an error reading the file.您还应该查看err以确定读取文件时是否有错误。

In this case, there is an error and thus data is undefined .在这种情况下,存在错误,因此dataundefined

The error is caused by you getting the filename wrong.该错误是由于您输入错误的文件名引起的。

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

req.url.split("/") gives you an array, but that isn't what you are reading the .length of. req.url.split("/")给你一个数组,但这不是你正在阅读的.length req.url

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

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