在不打开浏览器的情况下运行html响应

时间:2018-01-14 22:53:00

标签: javascript html node.js request

我尝试使用node.js(请求包)获取html文件的服务器响应,向其添加脚本并使用脚本运行此文件。

node.js

const request= require ('request')
const fs = require  ('fs')
request.get ('www.google.com', (err, data, body) => {
if (err) throw err
body+='<script src="script.js"></script>'
fs.writeFile ('h.html', body)
})

script.js

window.onLoad = () =>alert ('something')

如果不在html文件中保存响应并在浏览器中打开它,我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

var templateHtml = "<!DOCTYPE html><html><head></head><body>Your HTML</body></html>";
app.get('/your_resource',function(req,res){
    res.send(templateHtml);
});

当然,您需要在templateHtml脚本中替换。

请查看此answer以获取有关如何使用HTML模板的详细信息。

例如,假设您的项目中包含express-es6-template-engine

<强>的NodeJS

var express = require('express'),
    es6Renderer = require('express-es6-template-engine'),
    app = express();

app.engine('html', es6Renderer);
app.set('views', 'views');
app.set('view engine', 'html');

app.get('/', function (req, res) {
    res.render('index', {locals: {title: 'Welcome!', script: '<script>//script.js</script>'}});
});

app.listen(3000);

<强> HTML

<!DOCTYPE html>
<html>
<head>
    ${script}
</head>
<body>
<h1>${title}</h1>
</body>
</html>

希望有所帮助!