I'm new to Node.JS and I'm trying to run an example in the book Node.js The Right Way. The following code is saved in a file called watcher.js and the text file target.txt is in the same directory.
const fs = require('fs');
fs.watch('target.txt',function(){
console.log("File 'target.txt' just changed!");
});
console.log("Now watching target.txt for changes...");
When I run the file with the node command, the last line of the file, which should naturally be output first, is never seen. The log statement inside fs.watch() works fine and outputs the message every time the file changes.
There is a big gap between my version of Node.js (v6.11.0) and the one in the book (v0.10.20).
Is there something I am missing?
I've tested, your code works perfectly on node v7.1:
Related
Hope to get some help with what is my first question to the community...
I'm using the Tricentis Sample App to practice some testautomation with Cypress (javascript) and I'm having issues with the final step. (Downloading the mock invoice and checking the presence of it in the downloads folder)
//This function displays the "download pdf" button
function selectPriceOption(cy){
cy.get('#selectplatinum').check({force:true})
}
//this function is supposed to download the pdf
function downloadQuote(cy){
cy.wait(2000)
cy.get('#downloadquote').click()
cy.wait(20000)
}
//This function checks if file exists in the download folder
function checkFileExists(cy){
cy.readFile('C:/xxx/Documents/cypress/downloads/Tricentis_Insurance_Quote.pdf')
}
module.exports = {
enterAutoPage,
enterVehicleData,
enterInsuranceData,
enterProductData,
selectPriceOption,
checkFileExists,
downloadQuote
//sendQuote
}
When I'm running the script on npx cypress open mode, it downloads the pdf generated without a hitch. But as soon as I use npx cypress run --headed it doesn't manage to download the pdf file and as a consequence the test case throws a fail... Btw, I know the cy.wait command is not needed, it was just my last attempt to see if it needed additional waiting time. Still didn't work!
Now, here's what bugs me... If I run the script in open mode first, the download is successful and if I then go for the "run --headed" mode afterwards, it finds the file! I'm running trashAssetsBeforeRuns: false in the config file. So the check file function is working as intended. But when the folder is empty and I only use --headed mode then the download is NOT successful and the test case fails due the file is missing when the script reaches the last test step. I hope this explanation makes sense... #newbietechnicaltester
PS: Leaving the possibility open to something funky going on with the Tricentis site that is causing the code to not work as intended
I have a Node.js Application that I execute with systemctl start app.service on my server.
I configured my package.json correctly that on app start the log is being written in app.log with
node app.js > app.log 2>&1 the problem is now that with every restart the old log is being deleted and a new one is genereted. I want to keep my old log data for debugging purposes. How can I edit the log statement that the old log will be saved or the new log just appended? Is this possible?
I already searched in Stackoverflow and Google for a solution but did not find one. I was expecting to keep my old logs.
When using IO redirection, if you want to append to a file rather than overwrite the file, you need to use ">>" instead of ">". For example:
node app.js >> app.log
I'm working on a Discord Bot that has a variable 0-9999.
I need to be able to store that variable (let's say 9) into a .txt file,
and then whenever the Bot starts, it reads the file and sets the variable as
the first line of the text document.
So example:
Variable is 9. 9 is written to a text document on the first line.
Whenever I start the bot, Variable is set to the first line of text
document (9)
Not entirely sure how Discord bots work, but I know Discord is made with Electron and Node.js, so you could probably use the file system package (https://www.npmjs.com/package/fs)
Install it with:
npm install fs --save -g
You can read from the file like this:
// File system stuff.
var fs = require("fs");
// Get the text file and load it into a variable.
var file = fs.readFileSync("path/to/my/text/file.txt", "utf8");
And you can write to the file like this:
// Write the file
fs.writeFile("path/to/my/text/file.txt", myVariable, function (err) {
// Checks if there is an error
if (err) return console.log(err);
});
why not instead use cookies? If you're writing something for the browser you shouldn't store data in text files on the client's computer. If you are using nodejs for server code you could write text files but it would be better to use some sort of database.
I have JUST downloaded node.js and am having to work with their command line for the first time. It appears that every tutorial on the planet gives the same starter app.
It uses the code...
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
and wants me to save it to the file example.js.
The file can then be run by typing...
node example.js
but all the command line gives me is
...
The tutorials do not say WHERE I should save the file. To my C drive? To the same file as node.js? Anywhere?
I have tried all three and they don't seem to work. If there is any other solution, or simply something else I should be looking into and asking about, that help would be appreciated too. But at this point I honestly have no idea what the problem is, and there appears to be very few resources to help me here.
When you run node example.js from your prompt, it's assuming that example.js is in the current working directory.
To change your current working directory, use the change directory (cd) command:
cd C:\Projects\MyProject
node example.js
This is equivalent to
node C:\Projects\MyProject\example.js
Correct! you can save it any where and change to that directory by the (cd) command on node.js command prompt which will then give message says: "Server running at: 127.0.0.1:8124.
So point your browser to that address and you see your file.
I've been dealing with this for a long time, so any help is much appreciated. So, I'm downloading a file and saving it using PhantomJS and CasperJS. Let me point out that they aren't the issue. The file is downloaded without a problem.
The problem is that NodeJS won't recognize or open the file after it is downloaded. I can't fs.stat, fs.open, etc.. Nothing works.
I'll share the code in a second, but here's the log:
Here: bdTcK6hSdownload.csv
[ '2puzZMeLdownload.csv',
'2s5ICbKNdownload.csv',
'bdTcK6hSdownload.csv',
'izIfagwCdownload.csv' ]
fs.js:230
return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
Error: ENOENT, no such file or directory './caspertemp/bdTcK6hSdownload.csv'
at Object.openSync (fs.js:230:18)
at Object.processCSV (/Users/Home/dev/node_modules/inviter/index.js:64:29)
at /Users/Home/dev/node_modules/inviter/index.js:36:33
at ChildProcess.exithandler (child_process.js:281:7)
at ChildProcess.emit (events.js:70:17)
at maybeExit (child_process.js:361:16)
at Process.onexit (child_process.js:397:5)
As you can see, I'm printing out the created file name, then printing the contents of the directory and then trying to open the file. As you can see, bdTcK6hSdownload.csv exists in the directory but fails on open.
The simple code snippet is here:
console.log('Here: ' + filename);
filenames = fs.readdirSync('./caspertemp/');
console.log(filenames);
var fd = fs.openSync('./caspertemp/' + filename, 'r');
console.log(fd);
There's a bunch more going on before and after this but none of it matters since this basic function fails. Please help! This has been nagging for weeks.
My guess is that it's a discrepancy in current working directory. Are you starting the casperJS and node.js processes from the same directory? Do either of them change working directory at runtime? Try something like this, where node's __dirname will give you the directory path of the currently executing .js file
var path = require("path");
var filename = "bdTcK6hSdownload.csv";
var csvPath = path.resolve(path.join(__dirname, "caspertemp", filename));
console.log(csvPath);
Another possibility is timing.
I've had situations in the past where a file entry appears in the folder straight away but the file is unusable as the thing writing it has either not finished or not yet released it's handle. Under those conditions it isn't unusual to need to either defer processing or to do some other checks to see if things are ready.
On those occasions it may be that a restart 'fixes' things but only because as a side effect it either releases the handle or delays processing, so when your code trys again it's all fine.
This occurs only when you are giving wrong path. I have come across the same problem.
Initially I was running the file directly node xyz.js and required static files are in same repository. But When I do npm start, code was throwing above error :
fs.js 495
return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
**Error: ENOENT, no such file or directory**
Then I moved static resources, renamed path and It worked. Hope this may help you.
File extension could be entered twice hence not found. Navigate to the file directory with your command prompt and get the list of files in that directory
command:
dir
or
ls
Get the actual file name there and use it. In my case I had saved a text document as "readMe.txt" and on command prompt it appeared as "readMe.txt.txt". I did not have to append the file extension when saving and this created the problem.