Node.js强大的 make 变量与上传的文件 URL



嗨,我使用节点并且强大的表单提交文件,我需要将此文件的URL保存在全局变量中,以便以后将其与WATSON IBM图像识别API一起使用。

我是 node 的新手,所以我卡住了,变量名称是 newpath,我可以在提交表单后打印它,但以后无法访问变量。

我一定做错了什么,如果你能指出我的错误,我真的很感激。

const http = require('http');
var formidable = require('formidable');
const hostname = '127.0.0.1';
const port = 3500;
var fs = require('fs');
/// WATSON
var VisualRecognitionV3 = require('watson-developer-cloud/visual-recognition/v3');
var visualRecognition = new VisualRecognitionV3({
version: '2018-03-19',
iam_apikey: 'xxxxxxx'
});
// SERVER AND FORM
const server = http.createServer((req, res) => {
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.path;
var newpath = '/users/myuser/coding/visualr/' + files.filetoupload.name;
fs.rename(oldpath, newpath, function (err) {
if (err) throw err;
res.write('File uploaded and moved!');
// this is the path, variable newpath, but can't be accessed
// outside this function, tried to make it global but didn't work either
res.write('newpath');
res.end();
});

});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
});

var images_file = fs.createReadStream(newpath);
// I want to put the variable newpath in this function: but it doesn't work...
var params = {
images_file: images_file,
};
visualRecognition.classify(params, function(err, response) {
if (err)
console.log(err);
else
console.log(JSON.stringify(response, null, 2))
});

// ENDS
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});

变量是在if (req.url == '/fileupload') {...}块的上下文中定义的,因此在该块之外不可用。

若要在代码中的任何位置使用该变量,请在createServer块之外定义它:

var newpath; // this variable will have global context for this file
const server = http.createServer((req, res) => {
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.path;
// set the variable to its intended value here
newpath = '/users/myuser/coding/visualr/' + files.filetoupload.name;
fs.rename(oldpath, newpath, function (err) {
if (err) throw err;
res.write('File uploaded and moved!');
res.write('newpath');
res.end();
});
});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
});
console.log(newpath); // the variable should be available here, because of its context

最新更新