I am trying to get list of files in specified directory but its throwing error any idea what is implemented wrong in below code.
service.js
var fs = require('fs');
var path = require('path');
var async = require('async');
var filePath = path.resolve('./logs/dit/');
function checkSearchObj () {
fs.readdir(filePath,function (err, files) {
files.forEach(function(file) {
console.log(file);
});
})
}
checkSearchObj();
error
TypeError: Cannot read property 'forEach' of undefined
at C:\Users\sh529u\WebstormProjects\ulog\app\serverf
s:8:15
at FSReqWrap.oncomplete (fs.js:82:15)
Change this:
function checkSearchObj () {
fs.readdir(filePath,function (err, files) {
files.forEach(function(file) {
console.log(file);
});
})
}
to this:
function checkSearchObj () {
fs.readdir(filePath,function (err, files) {
if (err) {
console.log('Error:', err);
return;
}
files.forEach(function(file) {
console.log(file);
});
})
}
to see what's the error.
You need to check for errors instead of assuming that there was no error or otherwise you will try to access undefined variables and the only error you'll see is that you access undefined and not the actual error that's in err in this case.
Your callback will either get the err or the files but not both.
Update:
After changing the code to display error you got:
Error: { [Error: ENOENT: no such file or directory, scandir 'C:\Users\Web stormProjects\ulog\app\serverfiles\logs\dit'] errno: -4058, code: 'ENOENT', syscall: 'scandir', path: 'C:\\Users\\sh529u\\WebstormProjects\\ulog\\app\\serverfiles\\logs\\dit'
Which means that the program doesn't display the files in the directory because there is no such directory. Mystery solved. Now you can see how useful it is to actually check the errors.
Related
i am very new in JS and Nodejs and i am trying to
make a script that: every 1 sec it will read the files of the folder and after doing a specific task with the rows of every file will rename the files. The code bellow is my implementation:
const path = require('path');
const fs = require('fs');
const csv = require('csv-parser');
const { parse } = require("csv-parse");
const directoryPath = path.join(__dirname, 'Documents');
console.log(directoryPath);
function FTP(){
console.log("------------- SCAN THE DIRECTORY --------------------------")
fs.readdir(directoryPath, function (err, files) {
if (err) {
return console.log('Unable to scan directory: ' + err);
}
files.forEach(function (file) {
console.log(`${file}`)
fs.createReadStream(`${directoryPath}/${file}`)
.pipe(parse({ delimiter: `\t`, from_line: 2 }))
.on("data", function (row) {
let arrayToString = JSON.stringify(Object.assign({}, row)); // convert array to string
let stringToJsonObject_row = JSON.parse(arrayToString);
// DO A JOB ....
})
.on("end", function () {
console.log("finished");
})
.on("error", function (error) {
console.log(error.message);
})
});
})
fs.readdir(directoryPath, function (err, files) {
if (err) {
return console.log('Unable to scan directory: ' + err);
}
files.forEach(function (file) {
fs.rename(`${directoryPath}/${file}`,`${directoryPath}/${file}0`, () => {
console.log(`${file} Has been renamed`)});
});
});
}
setInterval(FTP, 1000);
THIS IS THE ERROR I GET:
/home/nikos/Desktop/TL2/FTP_server/Documents
------------- SCAN THE DIRECTORY --------------------------
sample_new
sample_new1
sample_new Has been renamed
sample_new1 Has been renamed
finished
finished
------------- SCAN THE DIRECTORY --------------------------
sample_new0
sample_new10
sample_new0 Has been renamed
sample_new10 Has been renamed
finished
finished
------------- SCAN THE DIRECTORY --------------------------
sample_new00
sample_new100
sample_new00 Has been renamed
sample_new100 Has been renamed
finished
finished
------------- SCAN THE DIRECTORY --------------------------
sample_new000
sample_new1000
sample_new000 Has been renamed
sample_new1000 Has been renamed
finished
finished
------------- SCAN THE DIRECTORY --------------------------
sample_new0000
sample_new10000
sample_new0000 Has been renamed
sample_new10000 Has been renamed
finished
finished
------------- SCAN THE DIRECTORY --------------------------
sample_new00000
sample_new100000
sample_new00000 Has been renamed
sample_new100000 Has been renamed
node:events:505
throw er; // Unhandled 'error' event
^
Error: ENOENT: no such file or directory, open '/home/nikos/Desktop/TL2/FTP_server/Documents/sample_new00000'
Emitted 'error' event on ReadStream instance at:
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: '/home/nikos/Desktop/TL2/FTP_server/Documents/sample_new00000'
}
[Done] exited with code=1 in 6.107 seconds
As it seems for a few iteration, it works but then i take the above error, can anyone explain me why?
Thank you!
As i can understand after reading about asynchronous programming, i think that due to nodejs is non-blocking, it does not wait for the IO, it goes to the bellow lines of code and when the file is going to be processed, it is already renamed by the renaming commands. Do you think this is a correct explanation?
I am trying to use the html-pdf node module to generate pdfs from html. I am currently running this using the cloud9 IDE.
My code is:
var fs = require("fs");
var pdf = require('html-pdf');
var html = fs.readFileSync('./test.html', {encoding: 'utf8'});
var options = { format: 'Letter' };
app.post('/pdf',function(req, res) {
pdf.create(html, options).toFile('./businesscard.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res); // { filename: '/app/businesscard.pdf' }
});
});
I get the following Error:
[Error: Fontconfig warning: ignoring C.UTF-8: not a valid language tag]
Does anyone know how i can resolve this issue?
This is due to a bug in fontconfig. You can see here
Open your terminal and execute locale -a you will see list of fonts. Then select it like LC_ALL=C
may it can help
I'm trying to copy an image from a folder to another using fs-extra module .
var fse = require('fs-extra');
function copyimage() {
fse.copy('mainisp.jpg', './test', function (err) {
if (err)
return console.error(err)
});
}
This is my directory
and this is the error I get all the time:
Error {errno: -4058, code: "ENOENT", syscall: "lstat", path:
"E:\mainisp.jpg", message: "ENOENT: no such file or directory, lstat
'E:\mainisp.jpg'"}
and by changing destination to ./test/ I get this error
Error {errno: -4058, code: "ENOENT", syscall: "lstat", path:
"E:\Development\Node apps\Node softwares\Digital_library\mainisp.jpg",
message: "ENOENT: no such file or directory, lstat 'E:\Devel…
apps\Node softwares\Digital_library\mainisp.jpg'"}
Note: I'm not testing this in browser. It's an Nwjs app and the pics of error attached are from Nwjs console.
You can do this using the native fs module easily using streams.
const fs = require('fs');
const path = require('path');
let filename = 'mainisp.jpg';
let src = path.join(__dirname, filename);
let destDir = path.join(__dirname, 'test');
fs.access(destDir, (err) => {
if(err)
fs.mkdirSync(destDir);
copyFile(src, path.join(destDir, filename));
});
function copyFile(src, dest) {
let readStream = fs.createReadStream(src);
readStream.once('error', (err) => {
console.log(err);
});
readStream.once('end', () => {
console.log('done copying');
});
readStream.pipe(fs.createWriteStream(dest));
}
Try:
var fs = require('fs-extra');
fs.copySync(path.resolve(__dirname,'./mainisp.jpg'), './test/mainisp.jpg');
As you can see in the error message, you're trying to read the file from E:\mainisp.jpg instead of the current directory.
You also need to specify the target path with the file, not only the destination folder.
Try:
const fs = require('fs');
fs.copyFileSync(src, dest);
I'm making a node/express app and am querying a test json file using npm request-promise. Node is spitting out the following error in my <title> tags:
Error: <title>Invalid URI "../testJSON/user.json"</title>
I believe my pathing is correct, so am unsure why it's an invalid URI.
I've also provided the entire project path URI with the same issue:
return rp('http://localhost:3000/app/testJSON/user.json');
User Service:
module.exports = {
getUserData: function(){
var options = {
uri : '../testJSON/user.json',
method : 'GET'
}
return rp(options);
}
}
User Controller:
var User = require('../services/User.service');
User.getUserData()
.then(function(data){
res.render('pages/userdata', {
title: 'User Data',
content: JSON.parse(data)
});
})
.catch(function(err){
console.log(err);
});
Pathing:
User Service: projectroot/app/services/userService.js
User json file: projectroot/app/testJSON/user.json
Update: trying with node fs to fetch local file
fs = require('fs');
module.exports.index = function (req, res) {
fs.readFile('../testJSON/user.json', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
res.render('pages/user', {
title: 'User',
content: JSON.parse(data)
});
});
...
Node error:
{ [Error: ENOENT, open '../testJSON/user.json'] errno: -2, code:
'ENOENT', path: '../testJSON/user.json' }
Relative paths (starting with ../ or ./) are relative to the current working directory. If you want to read a file relative to the current JS source file, you need to prefix the path with __dirname, which is the directory where the current JS source file resides:
fs.readFile(__dirname + '/../testJSON/user.json', ...);
Or the more elaborate (but probably more correct) way:
var path = require('path);
...
fs.readFile(path.join(__dirname, '../testJSON/user.json'), ...);
var conn = mongoose.createConnection(config.db);
conn.once('open', function (err) {
if (err) {
next(err);
return;
}
var source = fs.createReadStream(req.files.sample.path);
var gfs = Grid(conn.db, mongoose.mongo);
var id = mongoose.Types.ObjectId();
var target = gfs.createWriteStream({
_id: id,
filename: req.files.sample.name
});
source.pipe(target).on('close', function () {
project.documentation = id;
persistProject(req, res, next, project);
});
}
When I'm trying to upload it os showing the below error.
Terminating application: undefined
events.js:72
throw er; // Unhandled 'error' event
^
Error: ENOENT, open 'null/60c0f337f3413edbc5eb3bb27fa3269f'
Why this error is coming? Please help me to solve it.
ENOENT: Error, No Entry.
Or to make it more precise: req.files.sample.path seems not to be the correct path.
The error says 'null/...' - so maybe req.files.sample.path is empty?
If I would dig further, I would ask myself: Where do you "upload" to and what are the default paths there? Is that mongoDB working correctly on command line?