繁体   English   中英

将数据保存并加载到node.js服务器中,并将其传递到html5文件中

[英]Saving and loading data in a node.js server and passing it to an html5 file

因此,我对node.js和javascript非常陌生,并且通过按需加载html文件,使服务器性能很好。 这个html文件不包含任何自己的数据,它只是从Internet上获取并显示一些我写的图像和文本。 我决定让网站在打开时播放音频文件。 我知道可以使用html5中的<audio>标记轻松完成此操作,但是src =“”允许我从计算机中获取文件并将其放置在其中,当然,当我从另一台计算机打开网站时,显然找不到该文件因此无法播放。 我认为音频文件必须作为变量保存在服务器上,并传递到html文件的<audio src= >标记中。 我该怎么做呢? 这是一个.mp3(但我可以将其转换为任何其他音频格式)文件,大约30秒长。 我只希望它在从另一台计算机(通过Internet)加载网站时播放。 另外,我该如何处理图片或任何其他我不想从互联网上获取但要保留为服务器中数据的数据?

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

var simpleServer = http.createServer(function(request, response){
    response.writeHead(200, {"Content-Type":"text/html"});
    fs.readFile('./Picture.html', null, function(error, data){
        if(error){
            response.writeHead(404);
        } else{
            response.write(data);
        }
        response.end();
    })
});

simpleServer.listen(80, '0.0.0.0', function() {
    console.log('Listening to port:  ' + 80);
});

console.log("Server running...");

简短答案

完全不使用HTML,您也可以直接提供音频文件而不是Picture.html:

fs.readFile("./audiofile.mp3", function(error, data) {
    if (error) {
        response.writeHead(404);
    } else {
        response.writeHead(200, { "Content-Type": "audio/mpeg"});
        response.end(data, 'utf-8');
    }
});

注意:您必须将文件名audiofile.mp3和内容类型audio/mpeg替换为要发送的文件的相应值。

查看Mozilla的MIME类型完整列表,以获取文件扩展名及其相关内容类型的完整列表。

更好的答案:

http模块是一个很底层的模块,如果您正在学习,它会变得不必要地复杂。

您可以使用命令npm install express --saveexpress.js安装到项目中。

用express将您的代码简化为:

const express = require('express');
const app = express();
const port = 80;

app.get('/', (request, response) => {
  response.sendFile(__dirname + '/Picture.html');
});

// Anything put in the public folder is available to the world!
app.use(express.static(__dirname + '/public'));

app.listen(port, () => {
  console.log(`Listening on port: ${port}`)
});

然后,您只需要将所有文件放入项目目录下的“ public”文件夹中,就可以从HTML调用它们!

暂无
暂无

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

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