Error reading a file with Node js - 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.

Related

Why am I not able to upload file with following nodeJS code

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)

How to render a log file in browser through url using node js?

I am trying to render a log file in the browser by hitting a url. The log file is placed in my local (logs/app.log). I am stuck with this for a day.. Please find my node js code.
var app = express();
var path = require('path');
app.use('/logs', express.static(__dirname + '/logs'));
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
Please help me to resolve this issue.
You can write an API as below:
app.get('/logs', function (req, res, next) {
var filePath = "path to your log file";
res.sendFile(filePath, function (err) {
if (err) {
next(err);
} else {
console.log('Sent the logs..');
}
});
});

How to perform CRUD operation in node js with client api

This below code gives output for GET user list but i want
it also to delete and post some element in test.json file memory :
delete data using name i.e localhost:8080/alpha
and when we add user using post in api client it should save in test.json as new element with existing element
So can anyone edit the following code for me :)
test.json
[
{
"name":"alpha",
"password": "123"
},
{
"name":"beta",
"password": "321"
}
]
//main.js
var express = require('express');
var app = express();
var fs = require("fs");
app.get('/listUsers', function (req, res) {
fs.readFile(__dirname + "/" + "test.json", 'utf8', function (err, data) {
if (err) { return console.log(err); }
console.log("All users :" + data);
res.end(data);
});
});
app.delete('/:name', function (req, res) {
});
app.post('/postUser', function (req, res) {
});
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})

Node JS Stream Only works on first iteration

I have a simple node app that parses a csv file into a string. In my server file, I call a module that runs makes a stream and pipes it into my parser.
The problem is that is code works perfectly the first time it is run, but fails after that. I've gotten a "Write after End" error so I believe there is something wrong with the stream or parser variable not being reset properly after each use. Thanks for any help!
const express = require('express');
const app = express();
const path = require('path');
const port = process.env.PORT || 3000;
const formidable = require('formidable');
const parser = require('./csvparse.js');
const fs = require('fs');
//send the index page on a get request
app.listen(port, () => console.log('Example app listening on port: ' + port));
app.get('*', (req, res) => res.sendFile(path.join(__dirname + "/index.html")));
app.post('/upload', function(req, res) {
//upload the file from the html form
var form = new formidable.IncomingForm();
form.parse(req,function(err, fields, files) {
if (err) throw err;
//get the path to the uploaded file for the parser to use
var filePath = files.spinFile.path;
parser(filePath, function(data) {
if (data == null) {
res.sendFile(path.join(__dirname + "/index.html"));
}
res.send("<code>" + data + "</code>");
});
});
});
The module export function looks like this:
module.exports = function(filePath, cb) {
var stream = fs.createReadStream(filePath);
stream.pipe(parser);
//when the stream is done, songsLog is complete and ready to be returned
stream.on('close', function() {
cb(songsLog);
});
};
Try wrapping the contents of your module.exports in another function.
module.exports = function(filepath, cb) {
function parse(filepath) {
const stream = fs.createReadStream(filepath)
etc...
}
return {
parse
}
}
then from your route, call parser.parse('file.txt') and you should have a new read stream.

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;
});
});

Resources