twesix twesix - 2 years ago 237
Node.js Question

nodejs fs.openSync() with the flags 'a' fails to create a non-exist file

I want to write a log module for my app, which will create a non-exist file according to the time the module is initialized (with the init function in the module is called).

However, when I try to create the new log file with

It always gets an error.

I appreciate anyone that tell me why it fails to create the new file .

const fs=require('fs');
const path=require('path');
const moment=require('moment');
var time=function()
return moment().format('YYYY-MM-DD[_]hh:mm:ss:SSS');

var fd; // file descriptor

function init(log_dir)
var log_file_name=path.join(log_dir,time()+'.log');

The error is like below:

"C:\Program Files (x86)\JetBrains\PhpStorm 2016.1\bin\runnerw.exe" "C:\Program Files\nodejs\node.exe" index.js
return, stringToFlags(flags), mode);

Error: ENOENT: no such file or directory, open 'I:\twesix\lib\twesix_nodejs\log\2016-05-19_01:34:52:621.log'
at Error (native)
at Object.fs.openSync (fs.js:634:18)
at init (I:\twesix\lib\twesix_nodejs\log\index.js:15:16)
at Object.<anonymous> (I:\twesix\lib\twesix_nodejs\log\index.js:24:1)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:456:32)
at tryModuleLoad (module.js:415:12)
at Function.Module._load (module.js:407:3)
at Function.Module.runMain (module.js:575:10)

Process finished with exit code 1

I'm using windows 10 and my node.js version is 6.1.0

Answer Source

The problem is that the string returned by moment().format('YYYY-MM-DD[_]hh:mm:ss:SSS'); contains colons (:), which are not allowed in the name of the files on windows.

Change the format() to something that doesn't contain invalid characters for windows file names, like:

return moment().format('YYYY-MM-DD[_]hh-mm-ss-SSS');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download