如果文件在可能存在或不存在的目录中, 我如何使用 nodejs 写入文件?
类似这个问题:
< a href=" "https://stackoverflow.com/ questions/58744142/node-js-write-file-with-directories" >node.js 编写目录文件?
只要我需要一个解决方案来创建文件, 而节点- fs 只生成目录 。
如果文件在可能存在或不存在的目录中, 我如何使用 nodejs 写入文件?
类似这个问题:
< a href=" "https://stackoverflow.com/ questions/58744142/node-js-write-file-with-directories" >node.js 编写目录文件?
只要我需要一个解决方案来创建文件, 而节点- fs 只生成目录 。
发自FileUtils :
修改函数以满足您的需要! 但严重的是,使用模块而不是写自己的模块!
< a href=>"https://github.com/Gagle/Node-FileUtils/wiki/Reference#wiki-files-develop Timinary" rel=“noreferr” >decreate Tituty () :创建目录。如果前一个构成路径的目录不存在,它们就会被创建。默认权限: 0777 。
File.prototype.createDirectory = function (cb){
if (cb) cb = cb.bind (this);
if (!this._path){
if (cb) cb (NULL_PATH_ERROR, false);
return;
}
if (!canWriteSM (this._usablePath)){
if (cb) cb (SECURITY_WRITE_ERROR, false);
return;
}
var mkdirDeep = function (path, cb){
path.exists (function (exists){
if (exists) return cb (null, false);
FS.mkdir (path.getPath (), function (error){
if (!error) return cb (null, true);
var parent = path.getParentFile ();
if (parent === null) return cb (null, false);
mkdirDeep (parent, function (error, created){
if (created){
FS.mkdir (path.getPath (), function (error){
cb (error, !error);
});
}else{
parent.exists (function (exists){
if (!exists) return cb (null, false);
FS.mkdir (path.getPath (), function (error){
cb (error, !error);
});
});
}
});
});
});
};
mkdirDeep (this.getAbsoluteFile (), function (error, created){
if (cb) cb (error, created);
});
};
CreateNewFile ( :创建一个新文件。默认权限:0666。
File.prototype.createNewFile = function (cb){
if (cb) cb = cb.bind (this);
if (!this._path){
if (cb) cb (NULL_PATH_ERROR, false);
return;
}
if (!canWriteSM (this._usablePath)){
if (cb) cb (SECURITY_WRITE_ERROR, false);
return;
}
var path = this._usablePath;
PATH.exists (path, function (exists){
if (exists){
if (cb) cb (null, false);
}else{
var s = FS.createWriteStream (path);
s.on ("error", function (error){
if (cb) cb (error, false);
});
s.on ("close", function (){
if (cb) cb (null, true);
});
s.end ();
}
});
};
我写这封信是为了回答。
使用
var mkdirp = require("mkdirp")
var fs = require("fs")
var getDirName = require("path").dirname
function writeFile (path, contents, cb) {
mkdirp(getDirName(path), function (err) {
if (err) return cb(err)
fs.writeFile(path, contents, cb)
})
}
您可以使用类似 createWriteStream
的东西。
如果文件不存在, 它只会创建文件 。
由于 fs.covertys ()
() < a href="https://nodejs.org/api/fs.html#fs_fs_exists_path_callback" rel="nofolp" > deprecated ,这里是另一个使用 fs.access ()
和没有外部 npm 模块的Async 版本 :
"use strict";
var fs = require( fs );
var path = require( path );
var fileName = \tmp\a\b\c\d.txt ; // e.g. using Windows path separator
var contents = any content ;
createDirectoryAndFile(fileName, contents);
function createDirectoryAndFile(fileName, contents) {
var dirName = path.dirname(fileName);
var pathAsArray = dirName.split(path.sep);
_createDirectoryAndFile(pathAsArray, , function() {
fs.open(fileName, w+ , function(error, data) {
fs.writeFile(fileName, contents, function(error) {});
});
});
}
function _createDirectoryAndFile(pathAsArray, pathSoFar, createFile) {
if (!pathAsArray || pathAsArray.length === 0) {
createFile();
return;
}
var dir = pathAsArray.shift();
pathSoFar = pathSoFar + dir + path.sep;
fs.access(pathSoFar, function(error) {
if (error) { // directory does not exist
fs.mkdir(pathSoFar, function(error) {
if (!error) {
_createDirectoryAndFile(pathAsArray, pathSoFar, createFile);
}
});
} else {
_createDirectoryAndFile(pathAsArray, pathSoFar, createFile);
}
});
}
当然,需要通过增加错误处理和支持权限来改进这一点。
对于 TypeScript 用户来说, 我刚刚写了一本, 依据是mkdirP :
const _0777 = parseInt( 0777 , 8);
export function mkdirP(dir: string, opts: {
fs?: {
mkdir: (path: string | Buffer, mode: number,
callback?: (err?: NodeJS.ErrnoException) => void) => void,
stat: (path: string | Buffer,
callback?: (err: NodeJS.ErrnoException,
stats: fs.Stats) => any) => void
}, mode?: number}, f: Function, made?) {
dir = resolve(dir);
if (typeof opts === function ) {
f = <Function>opts;
opts = {};
}
else if (!opts || typeof opts !== object )
opts = {mode: <number>opts};
opts.mode = opts.mode || (_0777 & (~process.umask()));
opts.fs = opts.fs || fs;
if (!made) made = null;
const cb = f || (() => undefined);
opts.fs.mkdir(dir, opts.mode, function (error) {
if (!error) {
made = made || dir;
return cb(null, made);
}
switch (error.code) {
case ENOENT :
mkdirP(dirname(dir), opts, function (err, made) {
if (err) cb(err, made);
else mkdirP(dir, opts, cb, made);
});
break;
default:
opts.fs.stat(dir, function (e, stat) {
if (e || !stat.isDirectory()) cb(error || e, made);
else cb(null, made);
});
}
});
}
JavaScript 版本刚刚从签名中删除了批注类型, 即: 将前几行转向 : < code> (dir, options, mode, f, made) / code > 。
// Create parentDir recursively if it doesn t exist!
const parentDir = path/to/parent ;
parentDir.split( / ).forEach((dir, index, splits) => {
const curParent = splits.slice(0, index).join( / );
const dirPath = path.resolve(curParent, dir);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath);
}
});
// Create file.js inside the parentDir
fs.writeFileSync(`${parentDir}/file.js`, file Content , utf8 );
您可以使用 < a href=> "https://github.com/douzi8/file-system" rel=“ no follow” >https://github.com/douzi8/file-system
var file = require( file-system );
file.mkdir( 1/2/3/4/5 , [mode], function(err) {});
I am building a web application using NodeJS splitting the application into a back-end to handle database queries with MongoDB and a front end via a node based webserver that uses interactjs with ...
I have a working Express.js-based app running on Node.js. Now, I want to wrap it up with pm2. To do that, I ve defined ecosystem.json: { "apps": [ { "env": {...
I need to read a large JSON file (around 630MB) in Nodejs and insert each object to MongoDB. I ve read the answer here:Parse large JSON file in Nodejs. However, answers there are handling the JSON ...
I have an model called User but Sequelize looks for the table USERS whenever I am trying to save in the DB. Does anyone know how to set Sequelize to use singular table names? Thanks.
I don t fully get what Node.js is all about. Maybe it s because I am mainly a web based business application developer. What is it and what is the use of it? My understanding so far is that: The ...
I`ve been looking for a serverside language for some time, and python got my attention somewhat. But as I already know and love javascript, I now want learn to code on the server with js and node.js. ...
Is it possible to use jQuery selectors/DOM manipulation on the server-side using Node.js?
In nodejs, the only way to execute external commands is via sys.exec(cmd). I d like to call an external command and give it data via stdin. In nodejs there does yet not appear to be a way to open a ...