Why am I not able to upload file with following nodeJS code - node.js

I am trying to learn to upload a file using the following code:
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({dest:'./uploads/'}).single('file'));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.post('/file_upload', function (req, res) {
console.log(req.file.name);
console.log(req.file.path);
console.log(req.file.type);
var file = __dirname + "/" + req.file.name;
console.log("File Name: " file);
fs.readFile( req.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if( err ) {
console.log( err );
} else {
response = {
message:'File uploaded successfully',
filename:req.file.name
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
The file is successfully getting uploaded in /uploads directory, however, I am not able to open the file from there. Also, I am unable to print the name of the file when I try console.log(req.file.name); I get the output as undefined.
Any help will be appreciated. Thanks in advance.
EDIT: Console output as requested
Info: Start process (2:45:28 PM)
Example app listening at http://:::8081
undefined
uploads\3cbe4d0c18a778a9faddc6243c26b26a
undefined
File Name: undefined
{ message: 'File uploaded successfully', filename: undefined }
Process canceled
Info: End process (2:52:29 PM)

Related

SyntaxError: Unexpected token - in JSON at position 0,While uploading pdf files in postman

Controller.js
var multer = require('multer');
var upload = (req, res) => {
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/');
},
filename: function (req, file, cb) {
var dateTimestamp = Date.now();
cb(null, file.originalname.split('.')[file.originalname.split('.').length - 2] + '-' + dateTimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length - 1]);
}
});
var upload = multer({
storage: storage
}).single('file');
upload(req, res, function (err) {
console.log(req.file);
if(err) {
res.json({ error_code: 1, err_desc: err });
return;
}
res.json("File uploaded sucessfully");
});
};
module.exports ={
upload:upload
}
app.js
var mongoose = require("mongoose");
var multipart = require('connect-multiparty');
app.use(cors({origin:true, credentials:true}));
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb',extended: true}));
app.use(multipart({}));
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://127.0.0.1:27017/mydb");
var UploadRouter =require('./upload/uploadRouter/upload-doc-router');
app.use('/upload', UploadRouter);
var PORT = process.env.PORT || 4000;
app.listen(PORT, function(){
console.log('Running on Port 4000...');
});
router:
var express =require("express");
var URouter = express.Router();
var Upload = require('../uploadControllers/upload-doc-controllers');
URouter.route('/single/file').post(Upload.upload);
module.exports =URouter;
Above are the my code.I want to upload pdf,word document and store in one folder.when i test the api getting syntax error Unexpected token - in JSON at position 0 , JSON.parse (<anonymous>), createStrictSyntaxError like that shows error in postman .when i choose file in pdf then send the request to the api.
I removed headers and in body section i select form-data

Error reading a file with Node js

I can't read a file with this code that I've found on internet...
var express = require('express');
var app = express();
var fs = require('fs');
var port = 8080;
app.get('/', function(req, res) {
fs.readFile('./queries/anagconti_clienti_giorni.txt', 'utf8', function(err, data) {
if (err) {
res.send(err);
} else {
res.send(data);
}
});
});
var server = app.listen(port, function() {
console.log("Started on http://localhost:" + port);
});
The error that it give to me is:
{
"errno":-4058,
"code":"ENOENT",
"syscall":"open",
"path":"C:\Users\AlessandroGolin\Desktop\Mia\Visual_Studio\server_link\queries\anagconti_clienti_giorni.txt
"}
What could be causing this error??
Please cross check the path or permission of "./queries/anagconti_clienti_giorni.txt" file. If file not exist then create your "queries" folder at same level where your above code file exist.

Not able to see ipfs node id

Below is my app.js file. When I run the following code it shows "swarm listening on" and "file-path" and then nothing happens.
I am also running daemon on another command prompt listening api on 5001.
I think node is not getting initiated thats why it never becomes ready.
var express = require('express');
var app = express();
var ipfsAPI = require('ipfs-api')
var ipfs = ipfsAPI('localhost', '5001', {protocol: 'http'})
const IPFS = require('ipfs');
// Spawn your IPFS node \o/
const node = new IPFS();
var multer = require('multer');
var upload = multer({ dest: './z000000000'});
var fs = require('fs');
/** Permissible loading a single file,
the value of the attribute "name" in the form of "recfile". **/
var type = upload.single('filer');
app.post('/upload', type, function (req,res) {
/** When using the "single"
data come in "req.file" regardless of the attribute "name". **/
var tmp_path = req.file.path;
console.log(tmp_path);
//
node.on('ready', () => {
node.id((err, id) => {
if (err) {
return console.log(err)
}
console.log(id)
})
var data = fs.readFileSync('./'+tmp_path);
console.log("Synchronous read: " + data.toString());
let files = [
{
path: './'+tmp_path,
content: data
}
]
node.files.add(files, function (err, files) {
if (err) {
console.log(err);
} else {
console.log(files)
}
})
})
//
res.end();
});
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
Use ipfsAPI:
var ipfs = ipfsAPI('localhost', '5001', {protocol: 'http'}
To get the ID of node:
ipfs.id()
.then(res => {
showStatus(`daemon active\nid: ${res.ID}`, COLORS.success)
doYourWork()
})
.catch(err => {
showStatus('daemon inactive', COLORS.error)
console.error(err)
})
Find Documentation here: https://github.com/ipfs/js-ipfs-api

Node.js spawn ENOENT error

So I followed this answer and made it to the last step, correctly I think. But then what? I'm trying to run a node file, but it doesn't appear to be in the file listed at the PATH directory. How am I supposed to get it in that folder?
My node entry file:
'use strict';
var express = require("express");
var child_process = require("child_process");
var app = express();
app.get("/go", function(req, res, next) {
var stream = child_process.spawn("node file.js").on("error", function(error) {
console.log("Error!!! : " + error);
throw error;
});
});
app.get("/", function(req, res, next) {
console.log("Hit main page.");
res.end("Got me.");
});
app.listen( (process.env.PORT || 4000), function() {
console.log("Example app listening on Heroku port " + process.env.PORT + " or local port 4000!");
});
And file.js, the file I'm attempting to open:
'use strict';
function sayHello() {
console.log("Hello.");
}
sayHello();
In your spawn method, you should have:
app.get("/go", function(req, res, next) {
var stream = child_process.spawn("node", ["file.js"]).on("error", function(error) {
console.log("Error!!! : " + error);
throw error;
});
});

File download is not working with nodejs gridfs

i'm uploading images to gridfs-stream using node and express..uploading is working fine but am unable to download
app.post('/upload', function (req, res) {
var tempfile = req.files.displayImage.path;
var origname = req.files.displayImage.name;
var _id = guid();
var writestream = gfs.createWriteStream({
filename: _id
});
// open a stream to the temporary file created by Express...
fs.createReadStream(tempfile)
.on('end', function () {
res.send(_id);
})
.on('error', function () {
res.send('ERR');
})
// and pipe it to gfs
.pipe(writestream);
});
app.get('/download', function (req, res) {
// TODO: set proper mime type + filename, handle errors, etc...
gfs
// create a read stream from gfs...
.createReadStream({
filename: req.param('filename')
})
// and pipe it to Express' response
.pipe(res);
});
the above code is unable to download the image by this cmd download?filename=acf58ae4-c853-f9f3-5c66-c395b663298a
You might need to check your values in params. But hopefully this near minimal sample provides some help:
Update
And it has helped, because it highlights that you are looking up the _id as a filename. Instead you should be doing this:
.createReadStream({
_id: req.param('filename')
})
if not
.createReadStream({
_id: mongoose.Types.ObjectId(req.param('filename'))
})
Since the _id field is different to the filename
app.js
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var app = express();
var mongoose = require('mongoose');
var Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;
var conn = mongoose.createConnection('mongodb://localhost/mytest');
conn.once('open', function() {
console.log('opened connection');
gfs = Grid(conn.db);
// all environments
app.set('port', process.env.PORT || 3000);
app.use(express.logger('dev'));
app.use(app.router);
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
});
routes/index.js
exports.index = function(req, res){
res.set('Content-Type', 'image/jpeg');
gfs.createReadStream({
filename: 'receptor.jpg'
}).pipe(res);
};

Resources