我正在使用Meteor JS ...并且在我的Meteor应用程序中我使用节点来查询应用程序内不同目录的内容....
当我使用process.env.PWD查询文件夹的内容时,我得到的结果与使用process.cwd()查询文件夹结果时的结果不同.
var dirServer = process.env.PWD + '/server/';
var dirServerFiles = fs.readdirSync(dirServer);
console.log(dirServerFiles); //outputs: [ 'ephe', 'fixstars.cat', 'sepl_30.se1', 'server.js' ]
Run Code Online (Sandbox Code Playgroud)
VS
var serverFolderFilesDir = process.cwd() +"/app/server";
var serverFolderFiles = fs.readdirSync(serverFolderFilesDir);
console.log(serverFolderFiles); //outputs: [ 'server.js' ]
Run Code Online (Sandbox Code Playgroud)
使用process.cwd()只显示Meteor中的'server.js'.
为什么是这样?process.cwd()与process.env.PWD有什么不同?
我有
import fs from 'fs'
Run Code Online (Sandbox Code Playgroud)
在我的package.json我有
然后我运行命令
> npm i fs
> fs@0.0.2 node_modules/fsRun Code Online (Sandbox Code Playgroud)
接下来在我的React商店中导入'fs'模块
import fs from 'fs'Run Code Online (Sandbox Code Playgroud)
但是当我尝试使用fs时
我没有看到除了构造函数和一些其他__methods之外的方法.我没有看到方法createReadStream或任何其他文件操作方法.
有人知道出了什么问题吗?(使用Webpack)并可根据要求提供更多信息,但我到目前为止......
ps:为什么我可以npm i fs - 当我在其他帖子上阅读时,我不必这样做(使用节点5.5.0)
import Reflux from 'reflux'
import AddItemActions from '../actions/AddItemActions'
import request from 'superagent-bluebird-promise'
import fs from 'fs'
var ImageStore = Reflux.createStore({
init(){
.
.
.
},
decryptImage(file) {
var reader = new FileReader();
var info = {}
reader.onload = (output) => {
debugger
request.post("https://camfind.p.mashape.com/image_requests")
.set("X-Mashape-Key", "KEY")
.set("Content-Type", "application/x-www-form-urlencoded")
.set("Accept", "application/json")
.send({'focus': { 'x': 480}}) …Run Code Online (Sandbox Code Playgroud)我的脚本需要从JSON文件读取和写入.这没有问题.我在本地复制文件,编辑对象,然后将它们写回文件.但是,当我使用Ctrl + C关闭脚本并检查我的文件时,它[object, object]不是应该存在的实际对象.这不是每次都发生,但是很烦人,因为我的脚本依赖于这个文件.
有关如何防止这种错误关闭读者的任何想法?我在写作之前已经尝试检查类型,但它似乎没有多大帮助.
function writeConfig(obj) {
fs.writeFile('./config.json', obj, function (err) {
if (err) console.log(err);
});
}
Run Code Online (Sandbox Code Playgroud) 我想将我的gulpfile.js assets或src变量拆分成单独的文件,以便我可以更好地管理它们.例如:
....
var scripts = ['awful.js', 'lot.js', 'of.js', 'js.js', 'files.js']
....(somewhere down the line)
gulp.task('vendorjs', function() {
return gulp.src(scripts)
.pipe(concat('vendor.js'))
.pipe(rename({suffix: '.min'}))
.pipe(uglify())
.pipe(gulp.dest(paths.root + 'dist'))
.pipe(notify({ message: 'vendorjs task completed' }));
});
Run Code Online (Sandbox Code Playgroud)
所以我真的很感兴趣,如果有一种方法可以实际移动到一个单独的文件scripts变量,并能够从中访问它gulpfile.js.
我一直在寻找类似的东西:
require("fs").readFile('gulp/test.js', function(e, data) {
//(test.js would be the file that holds the scripts var)
});
Run Code Online (Sandbox Code Playgroud)
Howerver虽然它确实读取了文件的内容,但我仍然无法从中访问它gulpfile.js.任何提示或想法都非常感谢.
假设我们有这样一个程序:
// imagine the string1 to string1000 are very long strings, which will take a while to be written to file system
var arr = ["string1",...,"string1000"];
for (let i = 1; i < 1000; i++) {
fs.write("./same/path/file.txt", arr[i], {flag: "a"}});
}
Run Code Online (Sandbox Code Playgroud)
我的问题是, will string1 to string1000 be gurantted to append to the same file in order?
由于fs.write是异步函数,我不确定每次调用fs.write()是如何执行的.我假设对每个字符串的函数调用应该放在某处another thread(比如callstack?),一旦完成上一次调用,就可以执行下一个调用.
我不确定我的理解是否准确.
编辑1
在评论和答案中,我看到fs.write多次写入同一文件而不等待是不安全的callback.但是如何写入流?
如果我使用以下代码,它会保证写作的顺序吗?
// imagine the string1 to string1000 are very long strings, …Run Code Online (Sandbox Code Playgroud) 首先,我是新手es6和jest.
我有一个Logger实例化的类winston,我想测试它.
这是我的代码:
const winston = require('winston');
const fs = require('fs');
const path = require('path');
const config = require('../config.json');
class Logger {
constructor() {
Logger.createLogDir(Logger.logDir);
this.logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new (winston.transports.Console)({
format: winston.format.combine(
winston.format.colorize({ all: true }),
winston.format.simple(),
),
}),
new (winston.transports.File)({
filename: path.join(Logger.logDir, '/error.log'),
level: 'error',
}),
new (winston.transports.File)({
filename: path.join(Logger.logDir, '/info.log'),
level: 'info',
}),
new (winston.transports.File)({
filename: path.join(Logger.logDir, '/combined.log'),
}),
],
});
}
static get …Run Code Online (Sandbox Code Playgroud) 这是我的代码
const fs = require('fs');
const src = fs.createReadStream('bigfile3.txt');
const des = fs.createWriteStream('newTest.txt');
Run Code Online (Sandbox Code Playgroud)
我可以使用
src.on('data',(chunk)=>{
des.write(chunk);});
Run Code Online (Sandbox Code Playgroud)
或者
src.pipe(des);
Run Code Online (Sandbox Code Playgroud)
这两种处理文件操作的方式有什么区别吗?> "size" argument must not be larger than 2147483647每当我尝试使用大文件时,管道方法都会给我一个错误
。(~2GB)
谁能解释管道和流背后的工作?谢谢。
我想使用带有 fs 模块的节点 js 更改文本文件中的特定行。
有没有比将文件加载到数组更优雅的方法?
旧文件:
Line 1
Line 2
Line 3
Run Code Online (Sandbox Code Playgroud)
新文件:
Line 1
something new
Line 3
Run Code Online (Sandbox Code Playgroud)
感谢您的回复!
由于我的节点程序使用的模块,它需要 root 才能运行。这是因为它必须在端口 80 上运行 HTTP 服务器(正如您所知,像这样的较低端口需要 root 才能使用)。
但是,该程序还使用一种fs方法来创建文件。我不介意 root 是否是所有者,只要我可以更改权限......但这正是我遇到的障碍。
我正在使用该fs.mkdir函数创建一个目录,如下所示:
(假设这个文件名为create.js)
fs.mkdir(__dirname + "/.loud", 0777, function(err){
if (err) console.log("Failed to create file at " + __dirname + "/.loud");
});
Run Code Online (Sandbox Code Playgroud)
当执行它时(记住,通过 sudo,sudo node create.js)它实际上创建了文件夹...但是提供的权限(0777)是错误的!...
如果我没记错的话,7意味着读、写和执行。将它用于 3 个字段(777+ a 前导0将其表示为八进制)应该意味着每个人都可以在该文件夹内读取、写入和执行...但是这是我在检查文件夹权限时得到的结果:
fs.mkdir(__dirname + "/.loud", 0777, function(err){
if (err) console.log("Failed to create file at " + __dirname + "/.loud");
});
Run Code Online (Sandbox Code Playgroud)
因此,让我们分开开始的权限部分:
[imac] jamen : ~/Tests/mkdir …Run Code Online (Sandbox Code Playgroud) 我正在尝试执行以下操作:
问题是.on("end")在.on("data")处理完每一行之前触发。处理完所有行.on("end")后如何触发.on("data")?
下面是我正在谈论的一个简单的例子:
import parse from 'csv-parse';
var parser = parse({});
fs.createReadStream(this.upload.location)
.pipe(parser)
.on("data", line => {
var num = Math.floor((Math.random() * 100) + 1);
num = num % 3;
num = num * 1000;
setTimeout( () => {
console.log('data process complete');
}, num);
})
.on("end", () => {
console.log('Done: parseFile');
next(null);
});
Run Code Online (Sandbox Code Playgroud)
提前致谢。
fs ×10
node.js ×8
javascript ×5
stream ×2
asynchronous ×1
csv ×1
file ×1
filewriter ×1
gulp ×1
jestjs ×1
mashape ×1
meteor ×1
object ×1
permissions ×1
pipe ×1
reactjs ×1
unit-testing ×1
unix ×1
webpack ×1
winston ×1