Touch file then write to it in Node - node.js

How do I touch a file before writing to it?
Attempt
fs = require 'fs'
os = require 'os'
path = require 'path'
json_filepath = path.join os.tempdir(), 'cache', 'foo.json'
module.exports = (cb) ->
fs.open json_filepath, 'w', 438, (err) -> # Touch, also tried with node-touch
return cb err if err?
fs.writeFile json_filepath, {foo: 'bar'}, {}, (err) ->
#console.error 'Error writing cache: ', err
cb err
Error
{ [Error: ENOENT, open '/tmp/cache/foo.json']
errno: 34,
code: 'ENOENT',
path: '/tmp/cache/foo.json' }
Which is a POSIX error (linux manpage, additionally implemented for Windows, e.g.: in libuv). It means: No such file or directory

To answer original question
fs.writeFileSync('sporks','','utf8','a')

Why are you trying to open a file before calling fs.writeFile()? That is the wrong procedure and is likely causing at least part of your problem.
You should JUST call fs.writeFile(). That will create the file, write to it and close it all in one call. Opening the file first in w mode will likely cause a conflict with fs.writeFile() since the file is already open for writing elsewhere. Further, you never close the file you opened, thus leaking a file handle.
Just call fs.writeFile() with no fs.open() beforehand. That's how fs.writeFile() is written to work. One function call to do it all.
If you still get ENOENT after removing the fs.open() and you've cleared any orphaned file handles, then the remaining issue is likely that your path doesn't exist or you don't have the proper privileges on that path.
FYI, the path specified by:
path.join(os.tempdir(), "cache")
will not automatically exist. That would have to be something you created.

How about using this? File System Exists
fs.existsSync(path);
returns true if exists.

Related

Error: spawn EACCES in Node AWS Lambda function using child_process to call a binary file

I have this simplified code in a Node-based AWS Lambda function:
import { execFile } from 'child_process';
execFile('./node_modules/webp/bin/dwebp', ['./tmp/file.wepb', '-o',
'./tmp/newFile.png'], (error, stdout, stderr) => {
if (error) throw error;
});
As shown, I have a binary file in node_modules/webp/bin and I'm calling it with execFile to save an output in the folder ./tmp/ but I'm getting the error Error: spawn EACCES. Probably I'm not denied to access the folder ./tmp/ because my code is successfully writing files in it. I might be only denied to access to command dwebp itself. I don't know how to handle it. Hope you can help.
Adding my comment as an answer since it seemed to be the solution to your problem.
Writing to the folder means you have write permissions. You still might be lacking execution permissions.
You can edit permissions within Node using the chmod from the fs module. Documentation can be found here.

Opening an excel file with opn while another excel file is open, will execute code immediately without waiting

I'm using a library called opn. This makes it easier to spawn a child process to open a file in the main process of electron. I could use shell but I need to be able to detect when the file is closed which shell API doesn't provide.
Whenever I open an excel file and there are no other excel files opened, it will work fine and it will wait until I close the file before it resolve the promise. However, if there are other excel files open then it won't wait for the file to be closed and it will resolve the promise immediately.
I did some digging in the source code of the library and the command used to open the file is this for windows: start "" /wait name_of_file where name_of_file is a place holder for the file. The actual command the library executes is different but this one is enough for my use case. I ran into the same problem even when doing it manually without using the library. Maybe I should post this under super user instead of stackoverflow.
Here is the code that opens the file, wait for the file then executes callback.
opn(file, { app: 'EXCEL', wait: true }).then(() => {
const stream = fs.createReadStream(file);
papa.parse(stream, {
delimiter: ',',
complete: (results) => {
mainWindow.webContents.send('uploadNewIndexFileRen', key,
results.data);
},
error: (err) => {
throw err;
}
});
}).catch((error) => { throw error; });
UPDATE:
Here is a quick nodejs repo. All you need to do is clone/fork to check the problem or make a pull request then do npm install to download needed packages. To reproduce the exact problem that I have you might need to be in the following software versions:
Window 10
npm 5.5.1
node v8.9.1
excel 2013
opn 5.2.0 as seen in package.json
This is probably due to the way Excel handles files. I'm guessing Excel handles files with a single process so subsequent opening of files simply signals to the existing process that another files needs opening before closing.
You may be able to force Excel to open a new instance for each file by following these instructions.
Apparently using the /x command line switch will also start a new process:
excel.exe /x

Err. ENOENT when renaming a file in node.js

I'm trying to upload a file in my node/express app, but everytime I've got the ENOENT error when renaming the file. My code is that:
var tmp_path = req.files.file.path;
fs.rename(tmp_path, target_path, function (err) {
if(err) throw err;
...
});
where target_path will be the destination path. If I do:
console.log('exists ' + fs.existsSync(tmp_path));
then my server logs:
exists true
Also, listing the contents of tmp directory shows that the file is there. What's the problem?
FS methods like fs.rename which create, move or rename files expect that any directories in the path already exist. When they do not, you'll get an ENOENT. Since very often what you mean is "make this file -- and any directories in the path I specify for it" you may want to consider using an NPM library that abstracts access to fs with methods that take care of such things.
There are quite a few options. For example fs-extra is one of the better-tested libraries. Using fs-extra you can use ensureDir in that operation to make the directory structure first if it does not yet exist.

NodeJS child_process.execFile() always return Unknown system errno 193

Simply, i can't use the child_process.execFile(). It always contain error in callback.
child.js
console.log('I\'m child');
main.js
var cp = require('child_process');
cp.execFile('./child.js', function (err, stdout,stderr) {
console.log('Err: ',err);
console.log('STDerr: ',stderr);
});
The error object in the callback is
{ [Error: spawn Unknown system errno 193]
code: 'Unknown system errno 193',
errno: 'Unknown system errno 193',
syscall: 'spawn' }
The problem is that child.js is not a valid executable program. If you are on Linux or Mac you can fix that by writing this at the very top of child.js:
#!/usr/bin/env node
You will then need to say chmod +x child.js to make the file executable. The line is called a "shebang line" and it tells the system what interpreter to use to run the rest of the file. You'll need to have node in your $PATH for it to work.
If you don't like that, or are not using a Unix-like system, you can do this:
cp.execFile('/some/path/to/node', ['./child.js'])
The first argument must be the full path to your node interpreter program (perhaps node.exe on Windows, I don't know if that matters).
Finally, none of this really makes that much sense if you don't really need to launch a second node interpreter process. You can try including one file in the other--some ideas for that are here: How do I include a JavaScript file in another JavaScript file?

Node.js: Check if file is an symbolic link when iterating over directory with 'fs'

Supervisor is a package for Node.js that monitors files in your app directory for modifications and reloads the app when a modification occurs.
This script interprets symbolic links as regular files and logs out a warning. I would like to fork Supervisor so that either this can be fixed entirely or that a more descriptive warning is produced.
How can I use the File System module of Node.js to determine if a given file is really an symbolic link?
You can use fs.lstat and then call statis.isSymbolicLink() on the fs.Stats object that's passed into your lstat callback.
fs.lstat('myfilename', function(err, stats) {
console.log(stats.isSymbolicLink());
});
Seems like you can use isSymbolicLink()
const files = fs.readdirSync(dir, {encoding: 'utf8', withFileTypes: true});
files.forEach((file) => {
if (file.isSymbolicLink()) {
console.log('found symlink!');
}
}

Resources