I write server side application with express & node.js.
I have the next:
app.configure(function () {
app.use(express.bodyParser());
});
Everything works good, but:
As I understand, this method was deprecated.
The next method doesn't work well. It writes some random chars instead of writing the correct chars:
app.post('/randomWrite', function (req, res) {
var fileName = req.body.name;
var contentLength = parseInt(req.files.file._writeStream.bytesWritten);
var start = parseInt(req.body.chunk) * 102400;
var buffer = new Buffer(parseInt(req.files.file._writeStream.bytesWritten));
fs.open(req.files.file.path, 'r', function (status, fd) {
if (fd == null) {
console.log("Can't open the file with the fd");
return;
}
fileNameLocation = "./" + fileName;
fs.open(fileNameLocation, 'w+', function (err, fd1) {
fs.read(fd, buffer, 0, contentLength, start, function (err, bytesRead, buffer1) {
if (err)
console.log("ERROR: " + err);
fs.write(fd1, buffer1, 0, contentLength, start, function (err, bytesWrite, buffer) {
if (req.body.chunk == req.body.chunks - 1) {
fs.close(fd, function (err) {
})
fs.close(fd1, function (err) {
})
FileServer.prototype.returnResCodeWithId(res, 200, id);
} else {
fs.close(fd, function (err) {
})
fs.close(fd1, function (err) {
})
FileServer.prototype.returnResCode(res, 200);
}
})
})
})
})
Instead of writing in the correct offset, it seems that something get wrong and some text from the middleware (bodyParser) is written.
How can i change the express.bodyParser()? It will fix my problem with the writing?
You need to use the Body-parser middleware.
You can install it with
npm install body-parser
and include it with Express using
var bodyparser = require('body-parser');
app.use(bodyparser());
If you want file uploads too, then have a look at multer.
Related
I want to Use multer function in controller file But the problem is req.body got undefine when I use postman form-data body to upload images This is link to code that how I am using multer Function but I want use it in my controller
how I want to use it as you can see in below code
const multerHelper = require("../helpers/multer_helper");
Documents: async (req, res) => {
console.log(req.body)
if (!req.body.id) {
console.log(req.body)
logger.warn(error.MANDATORY_FIELDS);
return res.status(500).send(error.MANDATORY_FIELDS)
}
try {
multerHelper.createUserImage
let result = error.OK
logger.info(result);
return res.status(200).send(result)
} catch (err) {
logger.warn(err);
console.log(err);
return res.status(500).send(error.SERVER_ERROR)
}
}
but it throws error like req.body undefine
req.body empty image
postman form-data image
Anyone know how to do it
You can use multer functions and objects in only routes not in controller if you want to use it in controller you have to write storage and upload functions in controllers, here I have used multer error handling and I am uploading multiple images
Documents: async (req, res) => {
if (!req.headers.room_id) {
logger.warn(error.MANDATORY_FIELDS);
return res.status(500).send(error.MANDATORY_FIELDS)
}
try {
let storage = multer.diskStorage({
destination: function (req, file, cb) {
let id = req.headers.room_id;
let path = `tmp/daily_gasoline_report/${id}`;
fsextra.mkdirsSync(path);
cb(null, path);
},
filename: function (req, file, cb) {
// console.log(file);
let extArray = file.mimetype.split("/");
let extension = extArray[extArray.length - 1];
cb(null, file.fieldname + '-' + Date.now() + "." + extension);
}
})
var upload = multer({ storage: storage }).array('images', 100);
upload(req, res, function (err) {
if (err) {
console.log(err);
return res.end("Error uploading file.");
} else {
res.end("File has been uploaded");
}
});
let result = error.OK
logger.info(result);
return res.status(200).send(result)
} catch (err) {
logger.warn(err);
console.log(err);
return res.status(500).send(error.SERVER_ERROR)
}
}
Do you have a parser?
How do you parse the data?
Your gonna need to use something that gives you this data something like:
https://www.npmjs.com/package/express-fileupload
this package helps you to parse the form data and the files data itself.
I have a file that I am trying to write to from a post. Currently, the FS does not error nor does it write to file. However, when taking the same code from the deployed build and running it locally, it works. I even kept the file path consistent since it was throwing no permissions error at first. I ensured this file wrote to the same directory so each Filewrite Stream process would look at the same directory and file.
Local build:
var fs = require('fs');
const path = require('path');
var user_name = 'Password';
var password = 'test';
var errSTR = ""
fs.writeFile('C:\\hi.txt', 'Content to write', { flag: 'w' }, function(err) {
if (err)
return console.error(err);
fs.readFile('C:\\hi.txt', 'utf-8', function (err, data) {
if (err)
return console.error(err);
console.log(data);
});
});
Deployed Build:
app.route('/test')
.get(function(req, res) {
res.send('GET test');
})
.post(function(req, res) { // Start Post
var boolTry = false;
try {
boolTry = true;
var bool = false
var user_name = "Password"//req.body.user;
var password = "test"//req.body.password;
var errSTR = ""
fs.writeFile('C:\\hi.txt', user_name + password, { flag: 'w' }, function(err) {
if (err)
return console.error(err);
fs.readFile('C:\\hi.txt', 'utf-8', function (err, data) {
if (err)
return console.error(err);
res.send(500 + err);
console.log(data);
});
})
} catch (error) {
bool = true
errSTR = error
}
res.send('POST test' + " " + boolTry + " " + bool + " " + errSTR + ";")
})//END POST
.put(function(req, res) {
res.send('PUT test');
});
The local build will properly write to the file, while the dev build appears to do nothing. It should be noted by booleans were being used to understand how the file writer works but here is the server response from build: successful response POST test true false ;
Using:
IISNODE for iis: 7.x
Express: 4.16.2
node.js: v8.9.4
cors: 2.8.4
body-parser: 1.17.2
Sidenote: If you are confused by the writing portion of code, the intention was to write, check error then read, check error for assurance.
Update
Reoccurring error based on certain filewrite methods Error: EPERM: operation not permitted, open. Yes, all permissions for the directory are enabled along with ensuring read and write are checked.
I have a table in sql Server and I am trying to display it in web browser and apply datatable(jQuery) to it. Below code works fine as it gives the output in command line. But I'd have to get it on the browser(probably in json format).
I am using 'tedious' for connection as that's what I found in Express.js documentation.
var express = require('express');
var app = express();
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var config = {
userName: 'clientinfo',
password: 'clientinfo123',
server: 'USW20051234'
}
var connection = new Connection(config);
connection.on('connect', function (err) {
if (err) {
console.log(err);
} else {
executeStatement();
}
});
function executeStatement() {
request = new Request("SELECT * from dbo.Logs", function (err, rowCount) {
if (err) {
console.log(err);
} else {
console.log(rowCount+' rows');
}
connection.close();
});
request.on('row', function (columns) {
columns.forEach(function (column) {
if (column.value === null) {
console.log('NULL');
} else {
console.log(JSON.stringify(column.value));
}
});
});
connection.execSql(request);
}
You need to start HTTP server. As you already define APP try this
app.get('/urltest', (req, res) => {
res.send('hello from nodejs');
});
const PORT = 5000;
app.listen(PORT);
console.log('Listening on :' + PORT + '...');
and try http:localhost:5000/urltest on a browser
Thank You everyone for all the suggestions. I think "tedious" was giving me a hard time so I did npm install mssql and that worked like a charm.
Below is the link I referred to.
http://www.tutorialsteacher.com/nodejs/access-sql-server-in-nodejs
I'm trying to use ytdl-core module in order to download youtube audio to my local disk (some path on my computer).
I created an API to which I can call with the requested youtube url and the destination folder in which I want the file to be saved.
app.get('/api/downloadYoutubeVideo', function (req, res) {
var videoUrl = req.query.videoUrl;
var destDir = req.query.destDir;
ytdl.getInfo(videoUrl, function(err, info){
var videoName = info.title.replace('|','').toString('ascii');
var stream = ytdl(videoUrl, { filter: 'audioonly'})
.pipe(fs.createWriteStream(destDir + '\\' + videoName + '.mp3'));
stream.on('finish', function() {
res.writeHead(204);
res.end();
});
});
});
The problem is that when I call the api on my localhost (example: localhost:11245/api/downloadYoutubeVideo?videoUrl=https://www.youtube.com/watch?v=E5kJDWQSBUk&destDir=C:\test)
it works and the file indeed downloads to "C:\test".
But when I call to the api on my remote (example: http://sometest.cloudno.de/api/downloadYoutubeVideo?videoUrl=https://www.youtube.com/watch?v=02BAlrAkuCE&destDir=C:\test)
it doesnt create the file in the directory...
I have searched the answer but haven't found one...
Does C:\test already exist on your remote? If not you can't use fs.createWriteStream() until the directory has been created, it will not create the directory for you implicitly. Since you're not listening for an 'error' event, you wouldn't even know that was the problem since you're not capturing it.
The below code sample will check for the existence of destDir and if it doesn't exist will create it before proceeding.
const fs = require('fs');
const sep = require('path').sep;
function checkAndMakeDir(dir, cb) {
fs.access(dir, (err) => {
if (err)
fs.mkdir(dir, (err) => {
if (err)
return cb(err);
return cb();
});
else
return cb();
});
}
app.get('/api/downloadYoutubeVideo', function (req, res) {
let videoUrl = req.query.videoUrl;
let destDir = req.query.destDir;
checkAndMakeDir(destDir, (err) => {
if (err) {
res.writeHead(500);
return res.end();
}
ytdl.getInfo(videoUrl, function (err, info) {
let videoName = info.title.replace('|', '').toString('ascii');
let saveStream = fs.createWriteStream(`${destDir}${sep}${videoName}.mp3`);
saveStream.once('error', (err) => {
console.log(err);
res.writeHead(500);
return res.end();
});
saveStream.once('finish', () => {
res.writeHead(204);
return res.end();
});
ytdl(videoUrl, {filter: 'audioonly'})
.once('error', (err) => {
console.log('Read Stream Error', err);
res.writeHead(500);
return res.end();
})
.pipe(saveStream);
});
});
});
I am trying my hand at making a simple Node.js server without Express and this where I actually learn a bit more about the down and dirty of actually server files and data on requests based on paths request and basic HTTP stuff.
I have this straightforward server like so:
var http = require('http');
const PORT = 6969;
var allRoutes = require('./routes/all');
var server = http.createServer(allRoutes);
server.listen(PORT, function () {
console.log("Server listening on: http://localhost:%s", PORT);
});
and then I have one "middleware" function like so that handles all requests:
var url = require('url');
var fs = require('fs');
var appRootPath = require('app-root-path');
var path = require('path');
function handleRequest(req, res) {
var requestUrl = url.parse(req.url);
var fsPath;
if (requestUrl.pathname === '/') {
fsPath = path.resolve(appRootPath + '/view/index.html');
}
else {
fsPath = path.resolve(appRootPath + '/view/' + requestUrl.pathname);
}
fs.stat(fsPath, function (err, stat) {
if (err) {
console.log('error occurred...' + err);
return end(req, res);
}
try {
if (stat.isFile()) {
res.writeHead(200);
fs.createReadStream(fsPath).pipe(res);
}
else {
res.writeHead(500);
}
}
finally {
end(req, res);
}
});
}
function end(req, res) {
res.end();
}
module.exports = handleRequest;
the problem I am having is that my function doesn't seem to pipe the response to the browser. The browser shows no evidence of the data come from index.html, which is a barebones .html HTML5 file.
I stole the example, and am surprised it's not really working. Anyone have an idea? I know for sure that the fs.stat function is not experiencing an error and then it is streaming the index.html file, it just doesn't seem to be streaming to the right place...
For starters:
if (requestUrl.pathname = '/')
should be:
if (requestUrl.pathname === '/')
Your code was assigning, not comparing.
In addition, the .pipe() is asynchronous, but you are calling res.end() BEFORE it gets to do it's job in your finally{} block which closes the response stream and stops your pipe from doing anything. By default .pipe() will close the write stream by itself, so you don't need the res.end() at all when using .pipe().
You can change the code to this:
var url = require('url');
var fs = require('fs');
var appRootPath = require('app-root-path');
var path = require('path');
function handleRequest(req, res) {
var requestUrl = url.parse(req.url);
var fsPath;
if (requestUrl.pathname === '/') {
fsPath = path.resolve(appRootPath + '/view/index.html');
}
else {
fsPath = path.resolve(appRootPath + '/view/' + requestUrl.pathname);
}
fs.stat(fsPath, function (err, stat) {
if (err) {
console.log('error occurred...' + err);
return end(req, res);
}
try {
if (stat.isFile()) {
res.writeHead(200);
fs.createReadStream(fsPath).pipe(res);
}
else {
res.writeHead(500);
end(req.res);
}
}
catch(e) {
end(req, res);
}
});
}
function end(req, res) {
res.end();
}
module.exports = handleRequest;