[英]Run the script in node.js only after user select file in html
我正在使用node.js啟動服務,以便我的html可以與R代碼進行通信。 但是我在node.js上遇到了問題。 在我的html頁面中,我有一個瀏覽選擇按鈕,用戶可以使用它來選擇要讀取的數據文件,node.js會將文件名傳遞給R,因此R代碼將從所選數據文件中讀取數據然后運行分析模型。 但是由於我只具有Node.js的非常基礎的知識,所以目前,僅當我打開以下鏈接“ localhost:3000 / vis / rio”時,r代碼才會運行。 所以我的問題是,當選擇了數據文件后,如何使node.js在后台自動運行R代碼。 非常感謝您的提前幫助。
這是我的代碼:
Javascript-(將文件名發送到node.js):
var dataset,availableTags;
function handleFileSelect(evt) {
var file = evt.target.files[0];
$.ajax({ //getting the file name and update to node.js
type:'post',
url:"/getFileName",
data:{filename:file.name}
});
Papa.parse(file, { //papa is a library I used to read csv file
header: true,
dynamicTyping: true,
complete: function(results) {
dataset=results.data;
}
});
}
$(document).ready(function(){
$("#csv-file").change(handleFileSelect);
});
Node.js腳本:serve.js:
var express=require('express');
var path = require('path');
var vis = require('./routes/vis');
var index = require('./routes/index');
var bodyParser=require('body-parser');
var app=express();
require('./routes/main')(app);
app.get('/vis/rio',vis.rio); **//this is a package used to get connection with Rserve**
app.set('views',__dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded());
app.post("/getFileName",index.getFileName); **//this is the script to get the file name, it is from index.js**
var server=app.listen(3000,function(){
console.log("Express is running on port 3000");
});
index.js //這是用於獲取文件名的js文件
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
getFileName=function (req,res){
global.filename=req.body.filename; **//this is the global variable which stores the file name**
res.send('true');
};
module.exports = {router:router,getFileName:getFileName};
vis.js //這是用於與Rserve連接並將名稱傳遞給R代碼的文件
var rio = require("rio");
var arg={};
exports.rio = function(req, res){
arg={names:[global.filename]};
console.log(arg);
options = {
entryPoint:"nameoffile",
data: arg,
host : "127.0.0.1",
port : 6311,
callback: function (err, val) {
if (!err) {
console.log("RETURN:"+val);
return res.send({'success':true,'res':val});
} else {
console.log("ERROR:Rserve call failed")
return res.send({'success':false});
}
},
}
rio.enableDebug(true);
rio.sourceAndEval(__dirname + "/Rcode/test.R",options);
};
好像在任何時候都未調出/ vis / rio到服務器上。
您可能需要在客戶端再次調用/ vis / rio,或者如果您想使用該部分,則可以在index.js中導入/獲取該模塊並將其包含在getFileName中,然后僅調用在返回文件之前,請先在此處執行功能。 我對rio不太熟悉,但是在您的代碼中看不到該功能的任何訪問點。
編輯:如果我了解您要正確執行的操作,則始終可以在您的第一個Ajax調用的成功回調中發出第二個請求(至/ vis / rio)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.